Comment On Fine, I'll Handle Exceptions

Highly-paid consultants seem to get a lot of flak on this site, especially those who's number negation algorithms come with the prerequisite of installing an extra CPU fan. But certainly not all highly-paid (or, in Kent's case, highly-billed) consultants are bad; heck, Kent's job is to actually go in and make things better! Fancy that. [expand full text]
« PrevPage 1 | Page 2 | Page 3Next »

Re: Fine, I'll Handle Exceptions

2005-12-08 14:14 • by sodamnmad
I just want to say I'm glad I woke up early enough to be the first poster.

Re: Fine, I'll Handle Exceptions

2005-12-08 14:20 • by huboss
Wheeeee!
Now i know one more useful way to handle exceptionzz! *went modifying code in all progs*

Re: Fine, I'll Handle Exceptions

2005-12-08 14:27 • by mrsticks1982
52890 in reply to 52888

sodamnmad:
I just want to say I'm glad I woke up early enough to be the first poster.


 


always a good way to start the day ...

Re: Fine, I'll Handle Exceptions

2005-12-08 14:27 • by mrsticks1982
52891 in reply to 52890
Fire the idiot ... and throw them out the window

Re: Fine, I'll Handle Exceptions

2005-12-08 14:33 • by GoatCheez
52892 in reply to 52891
So THAT's how you do exception handling.... I thought you had to put code in the catch block to deal with the exception, but it turns out, the proper thing to do is to throw another GENERIC exception. That makes SOOOOOOOOOOO much sense.

(at least "it" isn't using exceptions for logic flow)

Re: Fine, I'll Handle Exceptions

2005-12-08 14:42 • by 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:



try {

  /* get some resource */

}

catch {

   LogError("Unable to get resource");

   throw;  /* doesn't matter what the exception is, if
we can't get the resource the whole program needs to abort */

}



Can anyone come up with a better name?

Re: Fine, I'll Handle Exceptions

2005-12-08 15:01 • by RevMike
WOW!  Look where he put the opening braces!  (And don't get me started on the two column indent!)

Re: Fine, I'll Handle Exceptions

2005-12-08 15:02 • by Anonymoose
52897 in reply to 52892
GoatCheez:
So THAT's how you do exception handling.... I
thought you had to put code in the catch block to deal with the
exception, but it turns out, the proper thing to do is to throw another
GENERIC exception. That makes SOOOOOOOOOOO much sense.

(at least "it" isn't using exceptions for logic flow)




Actually, in this situation, the throw statement will rethrow the current exception.  It's a C++ feature!



Hey, this guy is even being exception neutral!

Re: Fine, I'll Handle Exceptions

2005-12-08 15:14 • by Manni
52898 in reply to 52897
On Error Don't Do Anything Different

Re: Fine, I'll Handle Exceptions

2005-12-08 15:16 • by Disgruntled DBA
This almost goes one better than On Error Resume Next.  This is: On Error Resume Error.

Re: Fine, I'll Handle Exceptions

2005-12-08 15:21 • by Pope

This guy is awarded, in my book, for exceeding other's low expectations.


Shine on you crazy diamond!

Re: Fine, I'll Handle Exceptions

2005-12-08 15:24 • by MikeB
52902 in reply to 52899

Disgruntled DBA:
This almost goes one better than On Error Resume Next.  This is: On Error Resume Error.


"On Next Resume Error" would be even better. The CPU would get, like, 3 feet of air. No need for the extra fan.

Re: Fine, I'll Handle Exceptions

2005-12-08 15:43 • by Gene Wirchenko
52907 in reply to 52891
mrsticks1982:
Fire the idiot ... and throw them out the window


Your statement has been optimised to: "Fire the idiot out the window."  A PO has been filed with Purchasing for the necessary cannon.

Sincerely,

Gene Wirchenko

Re: Fine, I'll Handle Exceptions

2005-12-08 15:45 • by TankerJoe
52908 in reply to 52894

How about we name that scenario, "Mighty Morphing Power Exceptions"? [:D]

Re: Fine, I'll Handle Exceptions

2005-12-08 15:49 • by TankerJoe
52909 in reply to 52894

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:

try {
  /* get some resource */
}
catch {
   LogError("Unable to get resource");
   throw;  /* doesn't matter what the exception is, if we can't get the resource the whole program needs to abort */
}

Can anyone come up with a better name?


Wow, whodathunkit a "quote" button... errr ok, nevermind.  My vote is still for "Mighty Morphing Power Exceptions"


 


 


 

Re: Fine, I'll Handle Exceptions

2005-12-08 15:52 • by cconroy
52910 in reply to 52894
hank miller:
I think we need a new term to describe this
situation.   Something like exception passing code.

[snip]

Can anyone come up with a better name?




try - catch - somebody-else's-problem (a.k.a. "hot potato" exception handling)



Re: Fine, I'll Handle Exceptions

2005-12-08 15:53 • by akrotkov
52911 in reply to 52910
If it is that way, why not just define it as ;-)

function foo() throws Exception

That way, you don't even have to bother trying!

Re: Fine, I'll Handle Exceptions

2005-12-08 15:53 • by sammybaby

Jeez.


This is the Java equivalent of an "f*** you" followed by a poke in the eye.


I'd fire the ass who wrote this.

Re: Fine, I'll Handle Exceptions

2005-12-08 16:12 • by BlackTigerX
52914 in reply to 52892

GoatCheez:
So THAT's how you do exception handling.... I thought you had to put code in the catch block to deal with the exception, but it turns out, the proper thing to do is to throw another GENERIC exception. That makes SOOOOOOOOOOO much sense.


(at least "it" isn't using exceptions for logic flow)


actually that is not throwing ANOTHER generic exception, what he's doing is called re-raising, and is not a C++ language feature only, many languages do that

Re: Fine, I'll Handle Exceptions

2005-12-08 16:15 • by sao
52915 in reply to 52911
akrotkov:
If it is that way, why not just define it as ;-)

function foo() throws Exception

That way, you don't even have to bother trying!





Because he was trying to show he WASNT lazy. He HAD to try...

Re: Fine, I'll Handle Exceptions

2005-12-08 16:16 • by null
52916 in reply to 52912
sammybaby:

Jeez.


This is the Java equivalent of an "f*** you" followed by a poke in the eye.


I'd fire the ass who wrote this.



But, don't you get it? The rest of this guy's code was so brillant and perfect that it would never throw an exception to begin with! So writing code to handle non-existent exceptions would be a waste of this genius' time...


lol.


 


p.s. first post as a registered user! ;)

I like it

2005-12-08 16:29 • by null
52918 in reply to 52916

p.p.s.


When I am not looking at a specific posting, my taskbar button says


The Daily WTF (null)


I like it!

Re: Fine, I'll Handle Exceptions

2005-12-08 16:34 • by DevNull
52919 in reply to 52912
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.

Re: Fine, I'll Handle Exceptions

2005-12-08 16:49 • by richleick
52921 in reply to 52914
BlackTigerX:

GoatCheez:
So THAT's how you
do exception handling.... I thought you had to put code in the catch
block to deal with the exception, but it turns out, the proper thing to
do is to throw another GENERIC exception. That makes SOOOOOOOOOOO much
sense.


(at least "it" isn't using exceptions for logic flow)


actually that is not throwing ANOTHER generic exception, what he's
doing is called re-raising, and is not a C++ language feature only,
many languages do that





I blame this on the increasing popularity of Texas Hold 'Em and the
World Series of Poker.  I'll see your exception and raise it.

Re: Fine, I'll Handle Exceptions

2005-12-08 16:52 • by foxyshadis
52922 in reply to 52919
The code needs error handling, look at all those exceptions it's spewing.

try{try{try{try{...}
catch { throw; }
catch { throw; }
catch { throw; }
catch { throw; }


Dammit, it's still raising exceptions, I don't understand this at all.

tryit: try{ ... }
catch { goto tryit; throw; }

There we go, no more exceptions! This lame try-catch stuff sure is buggy and terrible at performance though, my low-level optimized VB software never hung up the system like that.

Re: Fine, I'll Handle Exceptions

2005-12-08 16:52 • by 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.

Re: Fine, I'll Handle Exceptions

2005-12-08 16:59 • by Joost_
52924 in reply to 52923
null:

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





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

Re: Fine, I'll Handle Exceptions

2005-12-08 17:03 • by 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.

Re: Fine, I'll Handle Exceptions

2005-12-08 17:10 • by null
52927 in reply to 52924
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.


import java.io.*;


public class Throw{
     public static void throwException(String filename) throws Exception{
          BufferedReader br = new BufferedReader(new FileReader(filename));
     }
     public static void main(String[] args) throws Exception{
          Throw.throwException("file doesn't exist");
     }
}

Re: Fine, I'll Handle Exceptions

2005-12-08 17:14 • by RevMike
52928 in reply to 52919
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.


Defenestration

2005-12-08 17:19 • by mhanoh

Defenestration is the only correct response to many a WTF nominated coder.

Re: Fine, I'll Handle Exceptions

2005-12-08 17:46 • by TankerJoe
52931 in reply to 52927
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.


import java.io.*;


public class Throw{
     public static void throwException(String filename) throws Exception{
          BufferedReader br = new BufferedReader(new FileReader(filename));
     }
     public static void main(String[] args) throws Exception{
          Throw.throwException("file doesn't exist");
     }
}



or maybe...


 


 


public class Throw{
     public static void throwException(Exception thrownException) throws Exception{
          try{
               throw thrownException
          }catch (Exception thrown){
               Throw.throwException(thrown);
          }
     }

     public static void main(String[] args) throws Exception{
          Throw.throwException(new Exception("Can't catch me!!!"));
     }
}


 


 


 

Re: Fine, I'll Handle Exceptions

2005-12-08 17:50 • by richleick
52932 in reply to 52928
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.


The only thing I read was



...Many of the operations and constructs of
the Java programming language can result in runtime exceptions.



What kind of language is this?



Ok, pipe down.  I've programmed in Java for awhile now.  And
aside from the fact that it's slow and often used in some type of Unix
envrionment, Java is actually an ok language.



Flame_On.equals("yes") ? lightFlame() : extinguishFlame();

Re: Fine, I'll Handle Exceptions

2005-12-08 17:51 • by RevMike
52933 in reply to 52931
TankerJoe:
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.


import java.io.*;


public class Throw{
     public static void throwException(String filename) throws Exception{
          BufferedReader br = new BufferedReader(new FileReader(filename));
     }
     public static void main(String[] args) throws Exception{
          Throw.throwException("file doesn't exist");
     }
}



or maybe...


 


 


public class Throw{
     public static void throwException(Exception thrownException) throws Exception{
          try{
               throw thrownException
          }catch (Exception thrown){
               Throw.throwException(thrown);
          }
     }

     public static void main(String[] args) throws Exception{
          Throw.throwException(new Exception("Can't catch me!!!"));
     }
}


 


 

Instead of catching Exceptions, catch and rethrow Throwable so that you'll get the errors too.

Re: Fine, I'll Handle Exceptions

2005-12-08 17:54 • by dobblego
52934 in reply to 52928
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.




I always find thedailywtf comments more amusing that the original post. It reminds me of what kind of industry I work in. Nevertheless, I will break my passive observations to point out a small inaccuracy in your assertions, for your own benefit, and that of readers, with the optimistic belief that I am not responding to an idiot (I sense intelligence!!). I often see that this specific issue causes many problems.

That is the notion of a 'method signature' (VMS 2.10.2 and JLS 8.4.2), which does not include any exceptions that have been declared on a method. Whether or not a method declares an exception is used for only two reasons a) compile-time checked exceptions as you have observed b) runtime reflective retrieval of those exceptions.

Some googling around will bring up a debate about the legitimacy of checked and unchecked exceptions. I won't go there, for brevity, suffice to say that I assert that both sides of the debate are completely wrong, unable to step outside of their context (Java/C#/etc.) and acknowledge the deeper flaws of the existing tools. Again, more evidence of the type of industry that I work in.

*reverts to tunnel vision*

Re: Fine, I'll Handle Exceptions

2005-12-08 18:06 • by BlackTigerX
52935 in reply to 52921
richleick:
BlackTigerX:

GoatCheez:
So THAT's how you do exception handling.... I thought you had to put code in the catch block to deal with the exception, but it turns out, the proper thing to do is to throw another GENERIC exception. That makes SOOOOOOOOOOO much sense.


(at least "it" isn't using exceptions for logic flow)


actually that is not throwing ANOTHER generic exception, what he's doing is called re-raising, and is not a C++ language feature only, many languages do that




I blame this on the increasing popularity of Texas Hold 'Em and the World Series of Poker.  I'll see your exception and raise it.


like everything else in programming, re-raising can be a good or a bad thing, of course this is one of those bad examples, but re-raising can be good like in the following example:


dbConnection.BeginTrans;


try {


//***some process


dbConnection.CommitTrans;


catch {


  dbConnection.RollbackTrans;


  throw; //we don't want to do the rest of the process if this db operation couldn't be done


}


and you would catch this exception at a higher level, but you made sure that you rolled back your transaction first

Re: Fine, I'll Handle Exceptions

2005-12-08 18:12 • by Omnifarious

I've seen a bunch of code just like this in code I inherited from the previous developer here. I decided to call it "Catch and Release exception handling".


Of course, what's even worse is the code that reads:

   try {

... // stuff
} catch (...) {
retval = BAD_RETVAL;
goto err;
}

err:
cleanup_resources();
ok:
return retval;


It's really kind of depressing. :-(


Re: Fine, I'll Handle Exceptions

2005-12-08 18:12 • by RevMike
52937 in reply to 52934
dobblego:
RevMike:
... 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....


I always find thedailywtf comments more amusing that the original post. It reminds me of what kind of industry I work in. Nevertheless, I will break my passive observations to point out a small inaccuracy in your assertions, for your own benefit, and that of readers, with the optimistic belief that I am not responding to an idiot (I sense intelligence!!). I often see that this specific issue causes many problems.

That is the notion of a 'method signature' (VMS 2.10.2 and JLS 8.4.2), which does not include any exceptions that have been declared on a method. Whether or not a method declares an exception is used for only two reasons a) compile-time checked exceptions as you have observed b) runtime reflective retrieval of those exceptions.

Some googling around will bring up a debate about the legitimacy of checked and unchecked exceptions. I won't go there, for brevity, suffice to say that I assert that both sides of the debate are completely wrong, unable to step outside of their context (Java/C#/etc.) and acknowledge the deeper flaws of the existing tools. Again, more evidence of the type of industry that I work in.

*reverts to tunnel vision*


Did you just use 3 paragraphs to point out to me that Checked Exceptions are not truly part of the method sugnature, in that they are not considered when resolving overloaded methods?  How dare you be pedantic when I was doing so first! :)

Re: Fine, I'll Handle Exceptions

2005-12-08 18:35 • by Xepol
It's more of an exception mishandler really.

Re: Fine, I'll Handle Exceptions

2005-12-08 19:07 • by Kooch
52942 in reply to 52940
At least the exception is rethrown. How many times have I seen this in code...



try {

    .... does something

} catch(Exception e) {

    // do nothing

}





Re: Fine, I'll Handle Exceptions

2005-12-08 19:39 • by RevMike
52943 in reply to 52942
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.

Re: Fine, I'll Handle Exceptions

2005-12-08 19:43 • by TankerJoe
52944 in reply to 52942

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

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



I agree.  I think this is much better:


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


Seriously, there are cases where this is appropriate.  For example, closing a jdbc connection that might already be closed....


Connection conn = null;
try{
     conn = ConnectionFactory();
     ...do the sql stuff
}catch(SQLException sqle){
    ... handle this
}finally{
     if (conn!=null){
          try{
               conn.close();
          }catch (SQLException ex){
               //ignore, it must already be closed....
          }
     }
}


 


 

Re: Fine, I'll Handle Exceptions

2005-12-08 19:47 • by TankerJoe
52945 in reply to 52943

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?


 

Re: Fine, I'll Handle Exceptions

2005-12-08 20:07 • by RevMike
52947 in reply to 52945
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.

Re: Fine, I'll Handle Exceptions

2005-12-08 20:22 • by kentcb
52948 in reply to 52947
I am the OP. The code is C#. As someone rightly pointed out, a plain
old throw statement is certainly useful in certain situations:



try

{

    //do some IO stuff

}

catch (IOException e)

{

    Log.LogError(...);

    throw;

}



However, in this case, nothing was being done. No logging or what-not,
just re-throwing the exception. The functional effect of the code was
zero. It may as well not have been there. Worse, it was placed at every
exception point in the code.



Kent

Re: Fine, I'll Handle Exceptions

2005-12-08 20:59 • by waynerad
Everyone is commenting on the modulo. But what about the gazillion time classes that all invoke each other's constructors and do time conversions just to store a single date/time??? That's the real crazy part man.

Re: Fine, I'll Handle Exceptions

2005-12-08 21:02 • by Xepol
52950 in reply to 52942

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....

Re: Fine, I'll Handle Exceptions

2005-12-08 21:02 • by waynerad
Oh CRAP I posted this on the wrong message. It was supposed to go on the previous wtf (the one about the modulo in the time classes). What happened was I couldn't post with firefox, so I fired up IE and posted the message, but I goofed, and this forum software won't let me delete it or move it to the right place.

Re: Fine, I'll Handle Exceptions

2005-12-08 21:08 • by Kooch
52954 in reply to 52943
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.




I agree. I even put a sentence saying that right after the code
snippet, but when I clicked post it came up with that sentence removed.




The real WTF here is this crappy forum software. How come there is no preview button? And whats with all the bugginess?

Re: Fine, I'll Handle Exceptions

2005-12-08 21:17 • by Kooch
52955 in reply to 52943
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.




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

« PrevPage 1 | Page 2 | Page 3Next »

Add Comment