• (cs) in reply to RevMike

    RevMike:
    Kooch:
    At least the exception is rethrown. How many times have I seen this in code...

    try {
        .... does something
    } catch(Exception e) {
        // do nothing
    }




    There are a fair number of cases where that is a reasonable thing to do.  For instance I have written plenty of "utility" jdbc stuff that attempts to close the result set, the statement, and the connection gracefully inside a finally block.  However, I'm just interested in doing my best effort at this, and I don't need to do anything special if they fail.

    try {
        // establish the connection
        // create the statement
        // execute the statement
        // iterate the result set
    }
    // catch blocks go here
    finally {
        try { rs.close(); } catch (Exception e) {}
        try { stmt.close(); } catch (Exception e) {}
        try { conn.close(); } catch (Exception e) {}
    }

    The fact that every goddamn method in the JDBC API throws SQLException is a WTF in its own right. There was a post above from the Java spec where they said they included unchecked exceptions in the language for the times that checked exceptions would be annoying/overkill. And they they go and make every method in JDBC throw a checked exception. Seriously... WTF?

  • (cs) in reply to Kooch

    Sorry for the double post.

  • (cs) in reply to Xepol
    Xepol:

    Kooch:
    At least the exception is rethrown. How many times have I seen this in code...

    try {
        .... does something
    } catch(Exception e) {
        // do nothing
    }


    So true... Perhaps we should suggest a language feature :

    try {

    } whocares;

    then the compiler can do any additional optimization that seems appropriate, or better yet, just a single whocares prefix to the line...

    whocares connection.close();

    I suppose then the compiler could even have a special debugging mode where it can log all the whocares for you "noone cared,  file.cs line #12, eioexception..."

    I wonder if we could talk Anders into it....



    I'll vote for that. Some of the classes in both the Java and .NET frameworks just throw exceptions needlessly and you quickly end up with really crappy looking code. Stuff like date parsing, etc - just return a null date don't throw a format exception at me!

    On that note, the new .NET 2 framework classes have stuff like this now for parsing values, e.g. Int32.TryParse() which returns a boolean to check if the parse was successful - the actual int is passed back as an out parameter. Having more than one return value is a really useful thing in a language.
  • (cs)

    [:O] Oh, I get it.  Because catching and rethrowing the exception is slower than just letting it continue up the stack on its own, the programmer is delaying the eminent crash of his/her program.  This could be very usefull if the project has some kind of uptime requirements.

    Brilliant!

  • (cs) in reply to RevMike
    RevMike:
    Kooch:
    At least the exception is rethrown. How many times have I seen this in code...

    try {
    .... does something
    } catch(Exception e) {
    // do nothing
    }




    There are a fair number of cases where that is a reasonable thing to do. For instance I have written plenty of "utility" jdbc stuff that attempts to close the result set, the statement, and the connection gracefully inside a finally block. However, I'm just interested in doing my best effort at this, and I don't need to do anything special if they fail.

    try {
    // establish the connection
    // create the statement
    // execute the statement
    // iterate the result set
    }
    // catch blocks go here
    finally {
    try { rs.close(); } catch (Exception e) {}
    try { stmt.close(); } catch (Exception e) {}
    try { conn.close(); } catch (Exception e) {}
    }

    The real interesting thing is that if I did propagate an exception from the finally block, an exception that I'm really interested in in from the try block will be discarded.

    wow... dude, if you're not going to do anything with the exception, then just put

    try {//your code here } catch {}

    no need for the Exception e

  • (cs) in reply to BlackTigerX

    WTF happened to my post?

    I was just saying, it is stupid to have this

    try { conn.close(); } catch (Exception e) {}

    if you really need that, then just do

    try { conn.close(); } catch {}

  • (cs) in reply to BlackTigerX
    BlackTigerX:
    WTF happened to my post?

    I was just saying, it is stupid to have this

    try { conn.close(); } catch (Exception e) {}

    if you really need that, then just do

    try { conn.close(); } catch {}



    Judging by your call to "close()" (as opposed to "Close()") you are writing in Java. If that's the case, I don't believe java allows a catch-all other than:

    catch (Exception e) {}

    even if you don't use e, you still have to declare it. If you're talking C#, you can:

    catch {}

    OR

    catch (Exception e) {}

    OR

    catch (Exception) {}

    Note there is no need to declare e if you don't use it. There is a difference between

    catch {}

    AND

    catch (Exception) {}

    catch {} will catch any thrown object regardless of whether it inherits from System.Exception. It is perfectly legal IL to throw a string, for example. That allows compatibility with languages such as C++. catch (Exception) {} will obviously only catch all exceptions.

    Note that .NET 2.0 (by default) now wraps non-exception throws in an Exception-inheriting wrapper so that catch {} and catch (Exception) {} will catch the same things.

    Kent

  • (cs) in reply to kentcb
    kentcb:
    If that's the case, I don't believe java allows a catch-all other than:

    catch (Exception e) {}


    Whoops, I mean:

    catch (Throwable t) {}

    which is the most generic Java catch.
  • (cs) in reply to Kooch
    Kooch:

    The fact that every goddamn method in the JDBC API throws SQLException is a WTF in its own right. There was a post above from the Java spec where they said they included unchecked exceptions in the language for the times that checked exceptions would be annoying/overkill. And they they go and make every method in JDBC throw a checked exception. Seriously... WTF?



    The problem is that if a method is not specified to possibly throw a SQLException in the Interface declaration, it cannot do so in the real implementation. So the creators of the JDBC interface had to go the save way, because who can say for sure that e.g. ResultSet.close() can never ever fail in any possible database system?
    Fact is, of course, that programs using JDBC have to catch a lot of errors that will never occur in the real world.
    That problem is one of the reasons why .net languages do not enforce exception handling like Java.
  • (cs) in reply to ammoQ
    ammoQ:

    The problem is that if a method is not specified to possibly throw a SQLException in the Interface declaration, it cannot do so in the real implementation.


    Sure it could:

    public class SQLException extends RuntimeException
    {
    ...

    Of course it's debatable whether this would really be have been better.

  • (cs) in reply to brazzy
    brazzy:
    ammoQ:

    The problem is that if a method is not specified to possibly throw a SQLException in the Interface declaration, it cannot do so in the real implementation.


    Sure it could:

    public class SQLException extends RuntimeException
    {
    ...

    Of course it's debatable whether this would really be have been better.



    I know, but that's so ridicoulus I hesitated to mention it ;-)
  • (cs) in reply to hank miller
    hank miller:
    I think we need a new term to describe this situation.   Something like exception passing code.

    I use something like, because I'd prefer a different term that didn't cover this case:


    You want a term that covers the OP's situation, but not the case where you do something useful before re-raising the exception?  How about "exception dodging"?  Or "exception evasion"?  "Exception shirking"?
  • (cs) in reply to RevMike
    RevMike:
    DevNull:
    Sorry, but I'd bet this is C#, not Java.  In Java, you still have to declare the function with a throws clause to get the compiler to accept the (re-)thrown exception.  True, this could be some chunk of code that someone suspects will throw an error (instead of an exception), but best practices in Java are not to catch errors, since an error by definition is supposed to be non-recoverable.

    Yes, there are times when I curse Java's "catch-all-exceptions" rule, but it at least discourages stupidity of this level.


    You're actually confusing Exception/Error with Checked Exception/Unchecked Exception.  Checked exceptions are declared as part of the method signature, and any method that calls that method must make some provision for handling the checked exception either by catching it or by declaring that it may be propagated in its own signature.  Unchecked exceptions are subclassed from RuntimeException.

    Java Language Specification:

    11.2.2 Why Runtime Exceptions are Not Checked

    The runtime exception classes (RuntimeException and its subclasses) are exempted from compile-time checking because, in the judgment of the designers of the Java programming language, having to declare such exceptions would not aid significantly in establishing the correctness of programs. Many of the operations and constructs of the Java programming language can result in runtime exceptions. The information available to a compiler, and the level of analysis the compiler performs, are usually not sufficient to establish that such run-time exceptions cannot occur, even though this may be obvious to the programmer. Requiring such exception classes to be declared would simply be an irritation to programmers.

    For example, certain code might implement a circular data structure that, by construction, can never involve null references; the programmer can then be certain that a NullPointerException cannot occur, but it would be difficult for a compiler to prove it. The theorem-proving technology that is needed to establish such global properties of data structures is beyond the scope of this specification.




    You're right.  I'd somehow convinced myself (without looking at the JavaDoc for both) that RuntimeException was a subclass of Error.  Oops.

    <leaving now to remove egg from face.>
  • (cs) in reply to Pope
    Pope:
    Lol, it was a good marketing ploy to break the comments for non-registered users... scroll up and look how many users registered just today.  Apparently there are more smart-asses out there than I realized.  Go, team, go.


    20 Points to Alex. Brillant!!!!
  • (cs) in reply to RevMike
    RevMike:
    TankerJoe:

    RevMike:
    Kooch:
    At least the exception is rethrown. How many times have I seen this in code...

    try {
        .... does something
    } catch(Exception e) {
        // do nothing
    }




    There are a fair number of cases where that is a reasonable thing to do.  For instance I have written plenty of "utility" jdbc stuff that attempts to close the result set, the statement, and the connection gracefully inside a finally block.  However, I'm just interested in doing my best effort at this, and I don't need to do anything special if they fail.

    try {
        // establish the connection
        // create the statement
        // execute the statement
        // iterate the result set
    }
    // catch blocks go here
    finally {
        try { rs.close(); } catch (Exception e) {}
        try { stmt.close(); } catch (Exception e) {}
        try { conn.close(); } catch (Exception e) {}
    }

    The real interesting thing is that if I did propagate an exception from the finally block, an exception that I'm really interested in in from the try block will be discarded.

     

    GET OUT OF MY HEAD!!!  [:P]

    Sheesh.... Where is my tin foil hat when I need it?

     



    What?  You are the one in my head!

    Seriously, a few differences deserve comment for the benefit of others:

    You check that the object references are not null before attempting to invoke the close method, then catch SQLException.  I ignore the fact that they may be null, but then catch Exception, which will catch both SQLException and NullPointerException.  My way is substantially less efficient than yours, and is innapropriate as part of a performance sensitive module.  Most of the time for me, this clean up is not performance sensistive so I sacrifice performance for simpler code.  Exception generation and propogation has a failrly high overhead, and so should only be used for actual exceptional situations, not as a general purpose tool to control program flow.

    I've compressed my try/catch into a single line while you have spread it across several lines.  You are doing the "right" thing.  I have compressed it into a single line because it is a trivial bit of code AND I repeatedly use this idiom.  If it wasn't trivial, or this was the only time it popped up, I would have formatted my code properly like you did.

     

    Good points all, and I agree that the way you handle this is significantly more readable.  My only question:  Is it really needed to close the ResultSet, then the Statement, and then the Connection?  Maybe I am wrong on this, but I was under the impression that by closing the Connection, you auto-magically close the other objects assiciated with it.  You might ba able to get away with code like this:

    finally {
        try { conn.close(); } catch (Exception e) {}
    }

     

  • (cs) in reply to TankerJoe
    TankerJoe:
    RevMike:
    TankerJoe:

    RevMike:
    Kooch:
    At least the exception is rethrown. How many times have I seen this in code...

    try {
        .... does something
    } catch(Exception e) {
        // do nothing
    }




    There are a fair number of cases where that is a reasonable thing to do.  For instance I have written plenty of "utility" jdbc stuff that attempts to close the result set, the statement, and the connection gracefully inside a finally block.  However, I'm just interested in doing my best effort at this, and I don't need to do anything special if they fail.

    try {
        // establish the connection
        // create the statement
        // execute the statement
        // iterate the result set
    }
    // catch blocks go here
    finally {
        try { rs.close(); } catch (Exception e) {}
        try { stmt.close(); } catch (Exception e) {}
        try { conn.close(); } catch (Exception e) {}
    }

    The real interesting thing is that if I did propagate an exception from the finally block, an exception that I'm really interested in in from the try block will be discarded.

     

    GET OUT OF MY HEAD!!!  [:P]

    Sheesh.... Where is my tin foil hat when I need it?

     



    What?  You are the one in my head!

    Seriously, a few differences deserve comment for the benefit of others:

    You check that the object references are not null before attempting to invoke the close method, then catch SQLException.  I ignore the fact that they may be null, but then catch Exception, which will catch both SQLException and NullPointerException.  My way is substantially less efficient than yours, and is innapropriate as part of a performance sensitive module.  Most of the time for me, this clean up is not performance sensistive so I sacrifice performance for simpler code.  Exception generation and propogation has a failrly high overhead, and so should only be used for actual exceptional situations, not as a general purpose tool to control program flow.

    I've compressed my try/catch into a single line while you have spread it across several lines.  You are doing the "right" thing.  I have compressed it into a single line because it is a trivial bit of code AND I repeatedly use this idiom.  If it wasn't trivial, or this was the only time it popped up, I would have formatted my code properly like you did.

     

    Good points all, and I agree that the way you handle this is significantly more readable.  My only question:  Is it really needed to close the ResultSet, then the Statement, and then the Connection?  Maybe I am wrong on this, but I was under the impression that by closing the Connection, you auto-magically close the other objects assiciated with it.  You might ba able to get away with code like this:

    finally {
        try { conn.close(); } catch (Exception e) {}
    }

     



    You are correct, calling close on the connection will cause any associated Statement.close() methods to be invoked, which will in turn cause any associated ResultSet.close() methods to be invoked.  I use this format because it doesn't hurt anything to do it this way and it is a reminder to free the other resources even if I don't close the connection.  If I want to perform several operations, I might cut and paste the entire try/catch/finally block a few times and then remove the Connection.close() calls.

    In that sense it is like always using braces around the body of an if, even if I'm only executing a single statement.  It makes it a little less likely that I might do the wrong thing down the road.
  • (cs) in reply to RevMike
    RevMike:
    TankerJoe:
    RevMike:
    TankerJoe:

    RevMike:
    Kooch:
    At least the exception is rethrown. How many times have I seen this in code...

    try {
        .... does something
    } catch(Exception e) {
        // do nothing
    }




    There are a fair number of cases where that is a reasonable thing to do.  For instance I have written plenty of "utility" jdbc stuff that attempts to close the result set, the statement, and the connection gracefully inside a finally block.  However, I'm just interested in doing my best effort at this, and I don't need to do anything special if they fail.

    try {
        // establish the connection
        // create the statement
        // execute the statement
        // iterate the result set
    }
    // catch blocks go here
    finally {
        try { rs.close(); } catch (Exception e) {}
        try { stmt.close(); } catch (Exception e) {}
        try { conn.close(); } catch (Exception e) {}
    }

    The real interesting thing is that if I did propagate an exception from the finally block, an exception that I'm really interested in in from the try block will be discarded.

     

    GET OUT OF MY HEAD!!!  [:P]

    Sheesh.... Where is my tin foil hat when I need it?

     



    What?  You are the one in my head!

    Seriously, a few differences deserve comment for the benefit of others:

    You check that the object references are not null before attempting to invoke the close method, then catch SQLException.  I ignore the fact that they may be null, but then catch Exception, which will catch both SQLException and NullPointerException.  My way is substantially less efficient than yours, and is innapropriate as part of a performance sensitive module.  Most of the time for me, this clean up is not performance sensistive so I sacrifice performance for simpler code.  Exception generation and propogation has a failrly high overhead, and so should only be used for actual exceptional situations, not as a general purpose tool to control program flow.

    I've compressed my try/catch into a single line while you have spread it across several lines.  You are doing the "right" thing.  I have compressed it into a single line because it is a trivial bit of code AND I repeatedly use this idiom.  If it wasn't trivial, or this was the only time it popped up, I would have formatted my code properly like you did.

     

    Good points all, and I agree that the way you handle this is significantly more readable.  My only question:  Is it really needed to close the ResultSet, then the Statement, and then the Connection?  Maybe I am wrong on this, but I was under the impression that by closing the Connection, you auto-magically close the other objects assiciated with it.  You might ba able to get away with code like this:

    finally {
        try { conn.close(); } catch (Exception e) {}
    }

     



    You are correct, calling close on the connection will cause any associated Statement.close() methods to be invoked, which will in turn cause any associated ResultSet.close() methods to be invoked.  I use this format because it doesn't hurt anything to do it this way and it is a reminder to free the other resources even if I don't close the connection.  If I want to perform several operations, I might cut and paste the entire try/catch/finally block a few times and then remove the Connection.close() calls.

    In that sense it is like always using braces around the body of an if, even if I'm only executing a single statement.  It makes it a little less likely that I might do the wrong thing down the road.

    The funny thing is that I too will always use braces around the if, even for the single statement scenario.  Are you sure that we are not the same person just logging in with different names to have a conversation with ourselves?  Either way, it sounds like I would much rather have to maintain your code than mine, (assuming that I had not written it).

  • (cs) in reply to ammoQ
    ammoQ:
    brazzy:
    ammoQ:

    The problem is that if a method is not specified to possibly throw a SQLException in the Interface declaration, it cannot do so in the real implementation.


    Sure it could:

    public class SQLException extends RuntimeException
    {
    ...

    Of course it's debatable whether this would really be have been better.



    I know, but that's so ridicoulus I hesitated to mention it ;-)


    Why is that ridiculous? I personally think it would be better. But brazzy is right in saying that its debatable. In fact there is a huge debate over wheter including checked exceptions in Java (I think its the only language that has them) was a good idea or a failed experiment. The C# designers considered it a failed experiment and decided not to include them in their language. Now I'm not against checked exceptions, I think they are a good idea most of the time, but when you go overboard with them like in JDBC, the arguments against them start to make sense.

    Let the C# vs Java war begin....
  • (cs) in reply to Xepol
    Xepol:
    try {

    } whocares;


    You know it is almost impossible to add a keyword. Even this one. So why not to remove it simply?

     try {
      ...
    }

    Same semantic. Catch them all.

    <font size="2">PS: Of course, I don't recommend it</font>
  • (cs)

    I can't defend the WTF, but if it is C# when you use throw it will throw the exception that was caught up to a higher level. [/master of the obvious]

            static void foo()
            {
                try
                {
                bar();
                }
                catch ( System.Exception ex )
                {
                    System.Diagnostics.Debug.WriteLine(ex.Message.ToString());
                }

            }

            static void bar()
            {
                try
                {
                    Exception e = new System.IO.FileNotFoundException("brillant!");
                    throw e;
                }
                catch
                {
                    throw;
                }

            }

    The catch in foo catches a FileNotFoundException.

    bah... back to creating my own WTF's!

  • (cs) in reply to Xepol
    Xepol:
    So true... Perhaps we should suggest a language feature :

    try {

    } whocares;

    then the compiler can do any additional optimization that seems appropriate, or better yet, just a single whocares prefix to the line...

    whocares connection.close();

    I suppose then the compiler could even have a special debugging mode where it can log all the whocares for you "noone cared,  file.cs line #12, eioexception..."

    I wonder if we could talk Anders into it....


    You mean like
    <font size="2">   on error resume next</font>
    ?

    It is sometimes useful.

    Sincerely,

    Gene Wirchenko

  • (cs) in reply to Kooch
    Kooch:
    ammoQ:
    brazzy:
    ammoQ:

    The problem is that if a method is not specified to possibly throw a SQLException in the Interface declaration, it cannot do so in the real implementation.


    Sure it could:

    public class SQLException extends RuntimeException
    {
    ...

    Of course it's debatable whether this would really be have been better.



    I know, but that's so ridicoulus I hesitated to mention it ;-)


    Why is that ridiculous? I personally think it would be better.


    It's ridicolous in the context of Java.
    Because it would abandon the whole concept how exception are handled in Java.
    RuntimeExceptions are used for cases that can easily ruled out by the programmer
    (like NullPointerException, ClassCastException, ArithmeticException); but that
    simply doesn't apply to SQLExceptions. No-one can rule out during compile time
    that the database cannot be reached, a table doesn't exist, a column name is misstyped, a duplicate key is created etc.

    But brazzy is right in saying that its debatable. In fact there is a huge debate over wheter including checked exceptions in Java (I think its the only language that has them) was a good idea or a failed experiment. The C# designers considered it a failed experiment and decided not to include them in their language. Now I'm not against checked exceptions, I think they are a good idea most of the time, but when you go overboard with them like in JDBC, the arguments against them start to make sense.

    Let the C# vs Java war begin....

    I think it will take some years of experience with large systems built in .net to find a conclusion who is right. Anyway, I think MS has a long history of valueing convenience more than safety, so it's logical for them to do it like this.
    Once a spaceship (programmed in C#) misses mars because of a unhandled exception, it will be proven that Java was right ;-)
  • (cs) in reply to ammoQ
    ammoQ:
    Kooch:

    But brazzy is right in saying that its debatable. In fact there is a huge debate over wheter including checked exceptions in Java (I think its the only language that has them) was a good idea or a failed experiment. The C# designers considered it a failed experiment and decided not to include them in their language. Now I'm not against checked exceptions, I think they are a good idea most of the time, but when you go overboard with them like in JDBC, the arguments against them start to make sense.

    Let the C# vs Java war begin....

    I think it will take some years of experience with large systems built in .net to find a conclusion who is right. Anyway, I think MS has a long history of valueing convenience more than safety, so it's logical for them to do it like this.
    Once a spaceship (programmed in C#) misses mars because of a unhandled exception, it will be proven that Java was right ;-)

    Keep in mind that safety was a major goal of Java from the very beginning, and a major reason that the language has been so successful.  If Java were to err, the fundamental philosophy of the language is that it is better to err on the side of caution.

  • (cs)

    This isn't a wtf , this is pretty standard,

    In C#,unlike java, almost any exception can be thrown at any time, it is pretty standard to to catch all exceptions and pass them back up to somplace you are prepared to deal with them. BTW throw re-throws the same exception so you wont lose stack-trace info.

    The other scenario where this makes sense is if this exception needs user interaction to resolve, something along the lines of a write erorr, or a file not found.

    public void LoadMyData(string FileName) {

    try {

    this.load(FileName);

    }catch {

    throw;

    }

    In this exmple there isnt anything LoadMyData can do except toss the excpetion up one level and let the calling class sort it out by repormpting the user.

    but in this casde I would have liked to see him deal with the specific file not found excpetion first

  • (cs) in reply to zoinks
    zoinks:

    This isn't a wtf , this is pretty standard,

    In C#,unlike java, almost any exception can be thrown at any time, it is pretty standard to to catch all exceptions and pass them back up to somplace you are prepared to deal with them. BTW throw re-throws the same exception so you wont lose stack-trace info.

    The other scenario where this makes sense is if this exception needs user interaction to resolve, something along the lines of a write erorr, or a file not found.

    public void LoadMyData(string FileName) {

    try {

    this.load(FileName);

    }catch {

    throw;

    }

    In this exmple there isnt anything LoadMyData can do except toss the excpetion up one level and let the calling class sort it out by repormpting the user.

    but in this casde I would have liked to see him deal with the specific file not found excpetion first



    I'm not an expert in C#, but wouldn't

    this.load(FileName);

    alone do exactly the same?

  • (cs) in reply to ammoQ

    Maybe the point is to have source level documentation of what method calls could throw an exception. In which case this would be the same:

    this.load(FileName);  // throws an exception


  • (cs) in reply to Gene Wirchenko

    Gene Wirchenko:

    You mean like
    <FONT size=2>   on error resume next</FONT>
    ?

    It is sometimes useful.

    Sincerely,

    Gene Wirchenko

    I've been waiting for someone to suggest it is the same thing.  No, on error resume next is like the ultimate app destabilizer.  You basically are telling the system that no exception should ever be handled under and condition.  Supressing all error handling is the exact OPPOSITE of what is happening here, and the oppositie of what we were suggesting (swalloing a suggestion for a single statement).

    On error resume next is what bad programers do to hide the fact that they don't have the first clue how to really program, and sadly it was aimed at the right crowd (vb programmers).  If VB had lacked that feature are required people to know how to handle errors, VB programmers wouldn't have gotten nearly reputation they did.

    It is ok to selective ignore "exceptions" that you have decided do not require additional handling, it is another thing entirely to decide that you just don't want to handle errors at alll, esp. in a language that does much of its compile&linking work at run time.

    Enough said.  Probably too much, in fact.

  • (cs) in reply to null
    null:
    Joost_:
    null:

    Poor handling of exceptions is often worse than no handling at all.



    Too bad Java won't let you not handle exceptions.

    You can always just throw it.

         public static void main(String[] args) throws Exception{
              Throw.throwException("file doesn't exist");
         }



    That's not 'not handling' it. See how the main method 'throws Exception'?
  • (cs) in reply to Joost_

    Joost_:


    That's not 'not handling' it. See how the main method 'throws Exception'?

    Lol. I guess, technically, no, you can't just completely ignore it. But throwing an exception doesn't quite equate to 'handling' it in my mind.

  • (cs) in reply to null

    I'll think of you when I'm writing a method that utilizes an output stream, sql statements and whatnot. I'll think, "LOOK AT ME MA! I'M NOT HANDLING EXCEPTIONS AT ALL!! I'M JUST THROWING THEM! NOW I CAN NOT HANDLE THEM ALL THE WAY UP TO THE MAIN METHOD!!"

    I hate being treated like a 5 year old when I'm programming. I'm perfectly happy with dealing with the consequences of not handling exceptions (it's generally a bad idea) but when I think it's not necessary, I don't need no stinking javac to tell me I should, no, must handle this IOException, that SQLException and that ConnectionException or whatever. I'd be perfectly happy to see them appear in little messageboxes or as big ass stack traces on the command line. Now you get all these people to write empty catch blocks. Or worse, catch blocks with error messages in them. Gah.

  • (cs) in reply to Xepol
    Xepol:

    Gene Wirchenko:

    You mean like
    <font size="2">   on error resume next</font>
    ?

    It is sometimes useful.

    I've been waiting for someone to suggest it is the same thing.  No, on error resume next is like the ultimate app destabilizer.  You basically are telling the system that no exception should ever be handled under and condition.

    No.  The error status is set.  That can be checked.  Sometimes, it is enough.
    This is not usually the case, but every so often, it is.

    Sincerely,

    Gene Wirchenko

  • (cs) in reply to Gene Wirchenko

    I remember seeing something like the following in an old classic asp app.  If Aaron R. is reading this, he'll remember them too.

    For i = 0 to 100

         ON ERROR RESUME NEXT
         Err.Clear
             ' Some Code

    Next

    "Can you find out why a feature that was added doesn't work properly?"   was what the manager would say. 

  • (cs) in reply to Joost_
    Joost_:
    I'll think of you when I'm writing a method that utilizes an output stream, sql statements and whatnot. I'll think, "LOOK AT ME MA! I'M NOT HANDLING EXCEPTIONS AT ALL!! I'M JUST THROWING THEM! NOW I CAN NOT HANDLE THEM ALL THE WAY UP TO THE MAIN METHOD!!"

    I hate being treated like a 5 year old when I'm programming. I'm perfectly happy with dealing with the consequences of not handling exceptions (it's generally a bad idea) but when I think it's not necessary, I don't need no stinking javac to tell me I should, no, must handle this IOException, that SQLException and that ConnectionException or whatever. I'd be perfectly happy to see them appear in little messageboxes or as big ass stack traces on the command line. Now you get all these people to write empty catch blocks. Or worse, catch blocks with error messages in them. Gah.


    Java doesn't force you to handle exceptions. Just declare for every method that it might throw that exception and everything is fine. Especially for those poor coworkers who are warned about the behaviour of your code that way.
  • (cs) in reply to ammoQ

    try
    {
       present xmasgift = new Bike();
       xmasgift.GiveTo(mySon);
    } catch (Exception eX)
    {
       if (eX is WrongSizeException)
       {
            present xmasgift = new Bike(mySon.Size);
            xmasgift.GiveTo(mySon);
        }
        else //ungrateful is the only other exception possibility to be thrown
        {
           mySon.Start(new TemperTantrum(eX.Message));
        }
    }

  • (cs) in reply to ammoQ
    ammoQ:
    zoinks:

    This isn't a wtf , this is pretty standard,

    In C#,unlike java, almost any exception can be thrown at any time, it is pretty standard to to catch all exceptions and pass them back up to somplace you are prepared to deal with them. BTW throw re-throws the same exception so you wont lose stack-trace info.

    The other scenario where this makes sense is if this exception needs user interaction to resolve, something along the lines of a write erorr, or a file not found.

    public void LoadMyData(string FileName) {

    try {

    this.load(FileName);

    }catch {

    throw;

    }

    In this exmple there isnt anything LoadMyData can do except toss the excpetion up one level and let the calling class sort it out by repormpting the user.

    but in this casde I would have liked to see him deal with the specific file not found excpetion first



    I'm not an expert in C#, but wouldn't

    this.load(FileName);

    alone do exactly the same?



    Yes, and therein lies the WTF. They are functionaly equivalent except the one with the catch and rethrow is more code and executes slower.

  • (cs) in reply to GoatCheez
    GoatCheez:
    try
    {
       present xmasgift = new Bike();
       xmasgift.GiveTo(mySon);
    } catch (Exception eX)
    {
       if (eX is WrongSizeException)
       {
            present xmasgift = new Bike(mySon.Size);
            xmasgift.GiveTo(mySon);
        }
        else //ungrateful is the only other exception possibility to be thrown
        {
           mySon.Start(new TemperTantrum(eX.Message));
        }
    }




    No, no, no, no, no!

    Presumably, the mySon object extends Thread and has already started,  the Runnable trantrum needs to be run asynchronously by the mySon thread.  Also,  just separate out the damn exception catch blocks... its ok... really... trust me.

    try
    {
      
    present xmasgift = new Bike();
       xmasgift.GiveTo(mySon);
    } catch (
    WrongSizeException wse)  //catch specific WrongSizeException
    {
            present xmasgift = new Bike(mySon.getSize());
            xmasgift.GiveTo(mySon);
     }
    catch (UngratefulException ue)  //ungrateful is the only other exception possibility to be thrown
        {
           mySon.throwTantrum(new TemperTantrum(ue.Message)); 
        }
    }






  • (cs) in reply to null
    null:

    I was helping a java 101 student yesterday. He had all - and I do mean all - of his code (which was doing file I/O's, initializations of objects, iterations through an array, etc.) in his main method in a try {} block. At the end, his catch statement went like this:

    catch(Exception e){
       System.out.println(e.getMessage());
    }

    Well, this was even less useful than simply throwing the exception, since the compiler would print out the exception message (in this case, simply the word 'null') with no information as to where the error was generated, what type of object was null, and so on.

    Poor handling of exceptions is often worse than no handling at all.




    Never heard of

    e.printStackTrace();
    ?
  • (cs) in reply to Xepol
    Xepol:

    Kooch:
    At least the exception is rethrown. How many times have I seen this in code...

    try {
        .... does something
    } catch(Exception e) {
        // do nothing
    }


    So true... Perhaps we should suggest a language feature :

    try {

    } whocares;

    then the compiler can do any additional optimization that seems appropriate, or better yet, just a single whocares prefix to the line...

    whocares connection.close();

    I suppose then the compiler could even have a special debugging mode where it can log all the whocares for you "noone cared,  file.cs line #12, eioexception..."

    I wonder if we could talk Anders into it....



    Or, if we are really feeling like it, we could introduce this syntax:

    attempt connection.close();

    That would actually be a great way to represent, in shorthand:

    try { connection.cose(); } catch (Exception e) {};
  • Ekevu (unregistered) in reply to akrotkov

    Sounds like a fun game to me. I used to do it with balls. I wonder if it's the same with errors?

  • (cs) in reply to akrotkov
    akrotkov:
    Xepol:

    Kooch:
    At least the exception is rethrown. How many times have I seen this in code...

    try {
        .... does something
    } catch(Exception e) {
        // do nothing
    }


    So true... Perhaps we should suggest a language feature :

    try {

    } whocares;

    then the compiler can do any additional optimization that seems appropriate, or better yet, just a single whocares prefix to the line...

    whocares connection.close();

    I suppose then the compiler could even have a special debugging mode where it can log all the whocares for you "noone cared,  file.cs line #12, eioexception..."

    I wonder if we could talk Anders into it....



    Or, if we are really feeling like it, we could introduce this syntax:

    attempt connection.close();

    That would actually be a great way to represent, in shorthand:

    try { connection.cose(); } catch (Exception e) {};


    I think it would be better to simply allow try {} without catch. No new keyword (always a problem, what if an existing program uses that as an identifier) and the meaning is the same.
  • (cs) in reply to ammoQ
    ammoQ:
    akrotkov:
    Xepol:

    Kooch:
    At least the exception is rethrown. How many times have I seen this in code...

    try {
        .... does something
    } catch(Exception e) {
        // do nothing
    }


    So true... Perhaps we should suggest a language feature :

    try {

    } whocares;

    then the compiler can do any additional optimization that seems appropriate, or better yet, just a single whocares prefix to the line...

    whocares connection.close();

    I suppose then the compiler could even have a special debugging mode where it can log all the whocares for you "noone cared,  file.cs line #12, eioexception..."

    I wonder if we could talk Anders into it....



    Or, if we are really feeling like it, we could introduce this syntax:

    attempt connection.close();

    That would actually be a great way to represent, in shorthand:

    try { connection.cose(); } catch (Exception e) {};


    I think it would be better to simply allow try {} without catch. No new keyword (always a problem, what if an existing program uses that as an identifier) and the meaning is the same.


    try connection.close();

    If that syntax would work, it would be great.
  • (cs) in reply to TankerJoe

    Of course! Silly mistake on my part ;-)

  • (cs) in reply to ammoQ

    I know that you have to declare that a method can throw an exception. That's exactly my point: all Java developers seem brainwashed on the idea that writing "throws Exception" is the same as 'not handling an exception'. Why is Java too stupid to figure out what else it could do with the exception except for throwing up?

  • moobar (unregistered) in reply to Joost_
    Joost_:
    Why is Java too stupid to figure out what else it could do with the exception except for throwing up?


    This shows you don't understand what exceptions are for.  Exceptions are, as their name imlpies, EXCEPTIONS.  They are thrown because they fall outside the expected operation of the code.  If the JVM could 'figure out what else to do' then it wouldn't be an exception in the first place.

  • (cs) in reply to Joost_
    Joost_:
    I know that you have to declare that a method can throw an exception. That's exactly my point: all Java developers seem brainwashed on the idea that writing "throws Exception" is the same as 'not handling an exception'.


    That's because the exception is not handled by writing "throws Exception". In my understanding, once an Exception is handled, it doesn't any longer break the program flow.


  • (cs) in reply to moobar
    Anonymous:
    Joost_:
    Why is Java too stupid to figure out what else it could do with the exception except for throwing up?


    This shows you don't understand what exceptions are for.  Exceptions are, as their name imlpies, EXCEPTIONS.  They are thrown because they fall outside the expected operation of the code.  If the JVM could 'figure out what else to do' then it wouldn't be an exception in the first place.



    You both are making good points, but you both need to refine your statements a bit.  The concept of an exception is a good and valid one, and the JVM is built 100% correct in this instance.  The problem is that many java api and many java programmers when writing their own methods overuse the exception pardigm.  Exceptions should be thrown when somethings "fall[s] outside the expected operation of the code."  To often, exceptions are used to indicate a "negative result" that should be well within the expected operation of the code.
  • (cs) in reply to RevMike

    RevMike:
    Anonymous:
    Joost_:
    Why is Java too stupid to figure out what else it could do with the exception except for throwing up?


    This shows you don't understand what exceptions are for.  Exceptions are, as their name imlpies, EXCEPTIONS.  They are thrown because they fall outside the expected operation of the code.  If the JVM could 'figure out what else to do' then it wouldn't be an exception in the first place.



    You both are making good points, but you both need to refine your statements a bit.  The concept of an exception is a good and valid one, and the JVM is built 100% correct in this instance.  The problem is that many java api and many java programmers when writing their own methods overuse the exception pardigm.  Exceptions should be thrown when somethings "fall[s] outside the expected operation of the code."  To often, exceptions are used to indicate a "negative result" that should be well within the expected operation of the code.

    The Java mandatory exception declaration concept blows and is definitely a failed experiment.  You can make nice-sounding arguments for it, but in the real world, it's just a pain in the ass with little or no payback.

    My favorite is java.io.FileNotFoundException..  Now how often is that really "outside the expected operation of the code?"  Come on java fanboys, be honest.

  • (cs) in reply to moobar
    moobar:
    Joost_:
    Why is Java too stupid to figure out what else it could do with the exception except for throwing up?


    This shows you don't understand what exceptions are for.  Exceptions are, as their name imlpies, EXCEPTIONS.  They are thrown because they fall outside the expected operation of the code.  If the JVM could 'figure out what else to do' then it wouldn't be an exception in the first place.



    I know very well what exceptions are for. I'm not asking Java to fix the error or clean up resources. There's a very good thing the JVM could do if I were to ignore the exception: print a nice error message, saving us the trouble of writing e.printStackTrace(). Most of the time I will just want to prevent the exception.

    Take the FileNotFound exception: what if I check beforehand if the file is there or not? Why am I still forced at gunpoint to catch an exception that can not occur? (Barring concurrency issues.)

    When dealing with streams, under what other circumstances will an IOException occur - when my 1 GB of memory is full? When my 200 GB hard disk is full? Thanks Java! My code is safe and all messed up with try/catch pest.

    Python is much nicer in this regard. By default, it will print a stack trace. If you catch the exception, you can do whatever you want; when you test your program and see an exception, it's up to you what you're going to do with it: you can prevent it by adding some check or you can catch the thing or leave it be. We're all grown-ups aren't we?
  • (cs) in reply to Joost_
    Joost_:
    Take the FileNotFound exception: what if I check beforehand if the file is there or not? Why am I still forced at gunpoint to catch an exception that can not occur? (Barring concurrency issues.)


    Well, how DO you "bar" concurrency issues? There's a number of security-creitical exploits that hinge on exactly that issue.

    Joost_:
    When dealing with streams, under what other circumstances will an IOException occur - when my 1 GB of memory is full? When my 200 GB hard disk is full?


    Well, what if that actually does happen? You want your server to happily keep accepting requests and drop them silently? Besides, IO isn't just files, and with any network-based IO you most definitely have the possibility of the connection breaking off at an arbitrary time.

    Joost_:
    Thanks Java! My code is safe and all messed up with try/catch pest.


    If so, it's because you're not using it appropriately. You do NOT have to catch exception in the method where they occur. In fact, the whole point is that you shouldn't,
     most of the time.

    Joost_:
    Python is much nicer in this regard. By default, it will print a stack trace. If you catch the exception, you can do whatever you want; when you test your program and see an exception, it's up to you what you're going to do with it: you can prevent it by adding some check or you can catch the thing or leave it be. We're all grown-ups aren't we?


    And we all have 100% test coverage. Yeah, sure...
  • (cs) in reply to JohnO
    JohnO:
    The Java mandatory exception declaration concept blows and is definitely a failed experiment.  You can make nice-sounding arguments for it, but in the real world, it's just a pain in the ass with little or no payback.


    OTOH the above isn't even a nice-sounding argument, it's no argument at all.

    JohnO:
    My favorite is java.io.FileNotFoundException..  Now how often is that really "outside the expected operation of the code?"  Come on java fanboys, be honest.

    Well, let's take a look at where it's used:

    http://java.sun.com/j2se/1.5.0/docs/api/java/io/class-use/FileNotFoundException.html

    Exclusively in constructors that take a path string or a File object (which is basically a path string with additional functionality). IMO if someone tries to open a file by specifying a path, then yes, he does indeed EXPECT that a file exists at that path.

    And what's your alternative solution?

Leave a comment on “Fine, I'll Handle Exceptions”

Log In or post as a guest

Replying to comment #:

« Return to Article