• anon (unregistered)

    The real WTF is that I'm fir .... that there are no other posts yet!

  • webrunner (unregistered)

    I think what we have here should be named "juggling". It throws and then immediately catches it's own exception.

    Now, there ARE actually reasons to squelch exceptions, even though it's generally a bad practice. Sometimes, the way you want to handle an given exception is just to do nothing. But why bother throwing it in the first place?

  • Chucara (unregistered) in reply to anon

    Sadly, what basically amounts to no exception-handling appears to be more the case than the exception (no pun intended).

    Of course, actually catching an exception and throwing a new in order to be able to do nothing with it is beyond reason.

  • Squiggle (cs) in reply to anon
    try { throw new Exception("Error inserting description!"); } catch (Exception ex) { }

    ...the mind baffles.

  • 604 (unregistered) in reply to Squiggle

    Good lord, please tell me that is the work of more than one brain dead developer. I can wrap my mind around the concept of one person writing throwing the new exception... and then someone else coming along and "fixing" it, but if this was written by a single coder I sure hope he was sniffing glue at the time.

  • brazzy (cs) in reply to webrunner

    If you can't do anything useful with an exception, at least log it. The only valid reason for silently swallowing exceptions is in unit tests where the exception can be the expected result and you only want the test to fail when it doesn't occur. If an API forces you to swallow useless exceptions as part of the normal flow of operations, then that API is crap.

  • Scotty (unregistered)

    Well, it's obviously all the compiler's fault :-). After the programmer added the code to throw a perfectly reasonable exception, the compiler probably complained that the method did not declare that it throws an exception. If the programer had added a throws modifier to the method, then every caller of the method would have required one as well, all the way up to the top of the stack. That's obviously way to much work, so the solution was to catch the exception. Apparently he or she never heard of RuntimeException...

  • FOO (unregistered)

    I've seen stuff like this before and attributed it to (perhaps) an ADVANCED JAVA technique. I'm happy to see that I'm not the first to exclaim WTF...

  • ry (unregistered) in reply to FOO

    I've seen this one way too many times. I think it stems from a lack of knowledge about the 'throws' keyword.

  • Greg (unregistered)

    I think the goal of the exception here is to document what the function should be doing. I can see a whole new paradigm coming up: DBE, documentation by exception. And a book: DBE Patterns.

    Remember folks, you heard it here first!

  • WIldpeaks (cs)

    If At First You Don't Succeed ... Skydiving is not for you.

  • itsmeyoufool (unregistered)

    Come on, it’s not really all that difficult to imagine. I’m not saying it began as something good, nesting try catches like that for a start is a little messy I feel. But it’s plausible that the developer was testing some rough code or program flow in the catch or something, which he/she later moved. A simple brain fart could account for neglecting to tidy everything up correctly and (not so) redundant checks could account for it passing though test.

  • Pon (unregistered) in reply to Greg
    Greg:
    I think the goal of the exception here is to document what the function should be doing. I can see a whole new paradigm coming up: DBE, documentation by exception. And a book: DBE Patterns.

    Remember folks, you heard it here first!

    Actually, I heard it first in the .Net Framework Design Guideleines :P

  • pointing out the obvious (unregistered) in reply to Squiggle

    perhaps a little silly, but i think the train of logic is:

    try { try somethhing } catch { try { throw ex; //if this fails, just squelch it } catch { //failed to even throw the exception //squelch it } }

    This developer may have been used to doing usefull work in his catch statements, and continued in this "design pattern" even though he was merely throwing the exception.

  • gruckiii (unregistered)

    I know in other languages it is permissible to catch the general Exception class.. but in Java I thought you were not supposed to (except in a few cases). Catching the general exception class in java also catches the out of memory and runtime exceptions which you can not do anything about.

    Encasing everything in a try catch(Exception) also makes your compiler not warn you about exceptions you could have handled more gracefully.

    IMO you should read the documentation of the methods you are using and catch the actual exceptions that they throw and handle them accordingly.

  • Raymond Chen (cs)

    The person sort of tried to follow a pattern and missed. The idea is to throw a custom exception and immediately catch it --- this has no effect at run time (aside from the performance hit) but you can tell the debugger to "break whenever an XYZ exception is thrown". Of course this requires you to throw a specific XYZ exception and not a generic Exception.

    If you just throw a generic Exception then all you get out of it is a rather complicated schema for trace logging.

  • Josh (unregistered) in reply to gruckiii
    gruckiii:
    I know in other languages it is permissible to catch the general Exception class.. but in Java I thought you were not supposed to (except in a few cases). Catching the general exception class in java also catches the out of memory and runtime exceptions which you can not do anything about.

    There are valid cases of catching Exception or even Throwable if you are trying to make a mission-critical system more fault tolerant. For example, a loop that runs generic services, each of which may fail for many reasons (including RuntimeExceptions). Of course, you would log those exceptions...

  • Angel (unregistered)

    Maybe he abused Exception handling as a way to omit input validation. Why bother with null checks, or verifying that the index of the class name substring ísn't -1? Who knows what kind of exceptions getDescription may throw? Handle all that? That's a pile of extra work! No dice, just catch anything and everything, and for good measure, throw an exception of your own and quickly swallow it again. Lazy logic at it's finest?

  • Loren Pechtel (unregistered) in reply to brazzy

    I've had to silently swallow one that came from a badly malformed e-mail header. Some spammer wrote utter garbage and caused my program to barf. Since I was only looking for certain e-mails anyway I could safely ignore anything that caused it to barf.

  • DancesWithPeons (unregistered) in reply to gruckiii
    gruckiii:
    I know in other languages it is permissible to catch the general Exception class.. but in Java I thought you were not supposed to (except in a few cases). Catching the general exception class in java also catches the out of memory and runtime exceptions which you can not do anything about.

    The Error class (and its subclasses) are thrown on out-of-memory and other conditions that are related to problems in the VM. The Exception class is for problems in the program.

    Exception and Error are both subclasses of Throwable, which is the real base class for all exceptions in Java. So catching Throwables is what would cause the problem you're thinking about.

    gruckiii:
    Encasing everything in a try catch(Exception) also makes your compiler not warn you about exceptions you could have handled more gracefully.

    IMO you should read the documentation of the methods you are using and catch the actual exceptions that they throw and handle them accordingly.

    That's great if the API you're using will never change. But what happens when it does change, and a condition that never caused problems before, now results in some exotic exception being thrown? (Quite possible, when some people subclass RuntimeException so that they don't have to declare "throws SomeKindOfException" for every method....)

  • Loren Pechtel (unregistered) in reply to Raymond Chen

    Re: Raymond Chen

    I think you hit on what's really going on here. I don't think this is a WTF, I think it's a piece of left-over debug code that didn't get removed.

  • Angel (unregistered) in reply to Loren Pechtel
    Loren Pechtel:
    Re: Raymond Chen

    I think you hit on what's really going on here. I don't think this is a WTF, I think it's a piece of left-over debug code that didn't get removed.

    Even without the nested try-catch this snippet is still plenty WTF.

  • CodeRage (cs)
    package test;
    
    public class paulaBean {
      private String paula = "Brillant";
    
      public String getPaula() {
        try {
           throw new Exception("Paula Forever");
        } catch (Exception e) {
           return paula;
        }
      }
    }
    
  • brendan (unregistered)

    I can see why you would want to re-throwing an exception to be handled by a different level. But I don't see the point in throwing and catching it at the same level. It might be more clear in the morning(it's 1:37am).

  • Magus (unregistered) in reply to Scotty
    Scotty:
    Apparently he or she never heard of RuntimeException...

    Noooooooo!!!!!

  • Sven (unregistered) in reply to webrunner

    That has got to be the longest way to write "NOP" I've ever seen.

    webrunner:
    Now, there ARE actually reasons to squelch exceptions, even though it's generally a bad practice. Sometimes, the way you want to handle an given exception is just to do nothing
    That is true, indeed, for "a given exception", but *any* exception? I'm sure that in Java there are similar objections to doing catch( Exception ) as there are in .Net, and catching the base Exception class and doing nothing has got to be a sin or something.
  • SomebodyElse (unregistered)
    That's great if the API you're using will never change. But what happens when it *does* change, and a condition that never caused problems before, now results in some exotic exception being thrown? (Quite possible, when some people subclass RuntimeException so that they don't have to declare "throws SomeKindOfException" for every method....)

    That is why you put the most specific exceptions higher up the list to catch, and close out the block with a catch(Exception e) as the last catch block. That way you are properly handling the current Exceptions, yet are still covering the possibility the the API changes to throw something different. Of course, If it changes to the point that the old exception is no longer thrown, or at least declared to be thrown, Then that would be a WTF

  • fennec (cs) in reply to webrunner
    webrunner:
    I think what we have here should be named "juggling". It throws and then immediately catches it's own exception.
    Well, I can think of some reasons you might want to do that - not that this is one of them, mind you, but... it could be used as a flow-control mechanism of sorts.
    try {
      ... stuff ...
      if(condition) // whoops! We should be doing XYZ instead
         throw new RandomFunkyException();
      ... more stuff ...
      if(condition) // okay, okay, NOW we do XYZ, okay?
         throw new RandomFunkyException();
      ... fancy stuff ...
      if(condition) // Last-minute XYZ action!!!
         throw new RandomFunkyException();
      ... crazy stuff ...
      // no XYZ here thank you
    } catch(RandomFunkyException RFE) {
      // Never mind!
      ... XYZ ...
      ... WTF ...
      .. EIEIO ..
    }
    

    It's like a GOTO. Perhaps it should be considered harmful. :)

  • deltreme (unregistered)

    "I don't really know what this function is for;"

    Duh, it does work! "doWork" - well chosen function name so the code speaks for itself!

  • been there (unregistered) in reply to deltreme

    Ideally, exception handling should be along the lines of:

    try { // some code } catch (SomeHighLevelException shle) { // handle it } catch (SomeLowerLevelException slle) { // handle it } catch (SomeLowLevelException slle) { // handle it } catch (StdFromPaula yuk) { reportHerAndDie(); } catch (Exception e) { // handle unexpected case when something external // causes this to break } catch (Throwable t) { // like catching ... in C++ - for really robust error // reporting (you usually can't fix these, but at least // you find out about them this way) }

  • AnonY (unregistered)

    Wow that is quite impressive and does make me worry about how people deal with exceptions. Really when dealing with Java there are a few core mantras to work with:

    1). Exceptions are not for logic. Catching ArrayIndexOutOfBoundsException as a way of knowing when you reach the end of a loop is just plain lazy and wrong ... I mean what if you actually have a real index bounds problem. I know sounds simple but it won't be long until someone posts a WTF showing this

    2). If you want to re-throw an exception as a different one then use the constructors which accept Exceptions as their arguments (some core Java classes do not do this but anything post 1.4 can do I think)

    3). Empty catch blocks are just plain wrong. Consider this scenario with JDBC:

    Connection conn = null;
    try {
      conn = getConncetion(); //Assume this is present
      conn.exceute("select 1 from dual"); //Hey guess what DB mostly use; mostly
    }
    catch(SQLException e) {
      throw new MyCustomException("Couldn't get 1 from dual", e);
    }
    finally {
      try {
        if(conn != null) conn.close();
      }
      catch(SQLException ex) {
        getLog().error("Couldn't close the connection", ex);
      }
    }
    

    Now most code might have opted not to put that log call in since if a connection cannot be returned then there's not a lot I can do programamtically. The thing is that if there is an exception here then I want to know about it; that kind of problem can be serious! (Oh yeah and for extra points if you chuck that finally block into another method and call that whenever you want to close a connection then everything becomes a lot clearer)

    4). If a programmer can recover from a thrown exception then checked exceptions can be very good. If you can't recover from it then why bog yourself down with multiple throws/re-throws? Just throw a custom subclass of RuntimeException and get told about it earlier rather than later

    5). If you're going to have your own exceptions then make sure they all inherit from a base exception. It'll make it easier if you want a "catch any kind of problem I cause" try-catch block

    There are more but I think everyone is a bit bored of me now :)

  • Gus (unregistered)

    Yeah. This stuff happens when person has unfortunately learned to program by fighting with the compile. These poor folks believe that if it compiles they've won and it's good enough to ship. First they write the part in the try block. Then they discover a case in which they get an exception, possibly a null pointer at

    String lastTag = "</" + obj.getClass().getName() + ">";

    Then not actually understanding anything beyond the fact that the exception percolating up is killing their code they squash it. But they did hear somewhere that you shouldn't just catch an exception and do nothing... so they try to rethrow it (ineptly) and the compiler complains that the method throws an undeclared exception.

    The compiler is standing in the way of progress, but they've seen this error before so they know how to best their arch enemy (the compiler). They catch the exception and viola! it compiles again.

    Of course a fix like this is slightly better than simply catching the exception because it provides ample evidence of incompetence (rather than simple forgetfulness or lazyness) with which to fire the person responsible, and some level of ammusement to the poor guy who just spent hours trying to figure out why occaisionally the stuff that happens in the doWork method doesn't seem to do happen at all, or perhaps only happens partially (since this is a lovely static mutator method).

  • anonymous (unregistered)

    I think what happened is this: the author wanted to catch the exception and replace it with some kind of context-specific message, i.e., "insert failed" rather than just NPE or whatever. It's perfectly OK to do this in a catch clause, but you would ordinarily wrap the original exception rather than replacing it. The way that it is done here the root cause of the exception is obliterated. (You want both "insert failed" and NPE, so you know why the insert failed.)

    However, they forgot to put a "throws" in the signature of the method itself, so the compiler flagged the unhandled exception...so they added the try with the empty catch to make it compile, which of course made the whole exercise pointless.

  • Dan (unregistered)

    I love how lazy or tired the programmer was.

    He just threw the exception with the description in the header (Insert description) probably without even really reading it.

    I love that. I may do that from now on.

  • twks (cs)

    A better way would be to handle the second exception as well.

    catch (Exception e) { try { throw new Exception("Error inserting description!"); } catch (Exception ex) { throw new Exception(Error catching exception from error caused by inserting description!"); } } }
  • Tom Dibble (unregistered)

    I vote for Raymond's explanation (which, quite sadly, was only voiced once after a dozen entries, seconded once, and has not been repeated again).

    The only reason to throw and then catch your own exception that I know of is to trigger a debugger event. And, not only is that the only reason I know of to do this, this is the only way I know of to do that (other than setting breakpoints, naturally, but those generally don't survive moving to another box). Most if not all debuggers can halt at the thrown exception (which is generally changed to specific exceptions by a programmer that uses libraries which throw exceptions left and right), so when running in debug this will halt it and the developer can then look at what caused the exception to be thrown.

    Personally, I believe a better approach to this would be to define a Debugger class, with a "halt" method which does the above (perhaps printing something to System.error in the catch block). This both makes the intent clearer ("Debugger.halt();" makes somewhat intuitive sense) and makes it easier to search and destroy such debug code before it gets checked in.

    Note that some languages include a system level call just for this purpose.

  • Tom (unregistered) in reply to Scotty
    Scotty:
    Well, it's obviously all the compiler's fault :-). After the programmer added the code to throw a perfectly reasonable exception, the compiler probably complained that the method did not declare that it throws an exception. If the programer had added a throws modifier to the method, then every caller of the method would have required one as well, all the way up to the top of the stack. That's obviously way to much work, so the solution was to catch the exception. Apparently he or she never heard of RuntimeException...

    Actually, yeah, I would guess that this person was using Eclipse or a similar IDE that warns you of uncaught or thrown exceptions, then suggests surrounding it with an empty try-catch block, or making the function throw exceptions. The programmer wasn't thinking and just wanted to get rid of the error, so he blindly followed the IDE's suggestion.

  • anony-mouse (unregistered) in reply to webrunner

    Maybe you didn't write the code that is throwing the exception.

  • aquanight (cs) in reply to brazzy
    brazzy:
    If you can't do anything useful with an exception, at least log it. The only valid reason for silently swallowing exceptions is in unit tests where the exception can be the expected result and you only want the test to fail when it doesn't occur. If an API forces you to swallow useless exceptions as part of the normal flow of operations, then that API is crap.

    java.io.StringReader. It only thows IOException if you close the reader and then try to read. IOException is a checked exception. Therefore, any call to StringReader.read() forces you to swallow an exception that will never happen. Especially true if wrapped over something like BufferedReader (necessary because StringReader doesn't have readLine() - another java WTF). ie:

    StringReader rd = new StringReader(paulaBean.getPaula());
    BufferedReader bufrd = new BufferedReader(rd);
    try
    {
      String paula = rd.readLine(); // This won't ever throw IOException, but readLine() says it can so we have to swallow it.
    }
    catch (IOException ioe)
    {
      // Swallow it. Alternatively... (yes, manually throwing Error could be a WTF, RuntimeException is probably better.)
      throw new Error("Creative message here.", ioe);
    }
    

    Don't ask me when you'd ever use StringReader. I can't think of a scenario off the top of my head.

    [edit: I guess you could argue for another thread closing the stream mid-read, but synchronizing would prevent that.]

  • Dan (unregistered)

    The code presented won't even compile since the method does not declare that it throws Exception.

    If it's the case that the code actually catches Exception and throws RuntimeException (which would not have to be declared in the method signature), it might be slightly more forgiveable.

  • PC (unregistered)

    This is a classic WTF.

  • Artemus Harper (unregistered)

    This is clearly a case of the programmer not understanding checked exceptions.

    First iteration:

    public void doStuff(Object obj, StringBuffer buf) { ... getStuff(obj); ... }

    public String getStuff(Object obj) { //some code that throws an exception }

    Result: Compile error: uncaught checked exception in method getStuff

    //V2 of getStuff: public String getStuff(Object obj) throws Exception { //some code that throws an exception }

    Result: Compiler error: uncaught checked exception in method doStuff

    //V2 of doStuff public void doStuff(Object obj, StringBuffer buf) throws Exception { ... getStuff(obj); ... }

    Result: Compiler error: uncaught checked exception in method <calling code>

    //V3 of doStuff public void doStuff(Object obj, StringBuffer buf) { try { ... } catch(Exception e) { throw new Exception("Bad stuff happens"); } }

    Result: Compiler error: uncaught checked exception in method doStuff

    Programmer then gives up and you see the code that it ends up with.

    What probably should have been done (for those who are lazy):

    public void doStuff(Object obj, StringBuffer buf) { try { ... } catch(Exception e) { throw new RuntimeException(e); } }

    which is fine since RuntimeException is not checked

  • brazzy (cs) in reply to aquanight
    aquanight:
    java.io.StringReader. It only thows IOException if you close the reader and then try to read. IOException is a checked exception. Therefore, any call to StringReader.read() forces you to swallow an exception that will never happen. Especially true if wrapped over something like BufferedReader (necessary because StringReader doesn't have readLine() - another java WTF). ie:

    (code)

    Don't ask me when you'd ever use StringReader. I can't think of a scenario off the top of my head.

    [edit: I guess you could argue for another thread closing the stream mid-read, but synchronizing would prevent that.]

    That's not what I meant. Arguably, checked exceptions are a bad concept, but if you accept them as valid, then there's nothing wrong with having an exception just because there might be situations where it cannot occur and still have to deal with them. And what if the programmer messes up, forgets synchronization and DOES end up calling read() on a closed stream? You'd want to know when that happens, wouldn't you?

    What I meant with crap API is one where in the normal course of events you are forced to catch exceptions that actually DO occur and do nothing with them - where the exception is the expected result but doesn't convey any information about actual exceptional circumstances.

    BTW, the purpose of StringReader is to be used as parameter for a method that accepts general Reader objects, which would have to be prepared to dealing with other (network- or file based) subclasses that very much can throw an IOException at any point.

  • aes (unregistered) in reply to Dan
    The code presented won't even compile since the method does not declare that it throws Exception.

    Because it doesn't.

  • Christophe (unregistered) in reply to FOO
    FOO:
    I've seen stuff like this before and attributed it to (perhaps) an ADVANCED JAVA technique. I'm happy to see that I'm not the first to exclaim WTF...
    Probably from a Highly Paid Consultant with 25 years Java experience.
  • Harry (unregistered) in reply to DancesWithPeons
    DancesWithPeons:
    That's great if the API you're using will never change. But what happens when it *does* change, and a condition that never caused problems before, now results in some exotic exception being thrown? (Quite possible, when some people subclass RuntimeException so that they don't have to declare "throws SomeKindOfException" for every method....)

    This is why Java added the concept of root cause exceptions. Normally what I do is define an application specific exception like BlewChunksWhileProcessingXXXException() that percolates up through the framework. Then in the code we have:

    try { .... some code } catch (cdiEx CantDoItException) { throw new BlewChunksWhileProcessingXXXException("Blew While User Did Something Stupid PEBKAC ERR 73", cdiEx ) }

    Then you isolate your framework from code changes that introduce new exception types and still get what happened in the stack trace.

  • Worker Bee (unregistered) in reply to anon

    Nah, the real WTF is that I remembered that I hadn't come here to look for today's WTF when I was browsing through some code at work...

    Well, it's pathetic, at least. Now, if you'll excuse me, I should get back to figuring out what the developer who wrote

  • lmollea (unregistered)

    I remember a code from a terrible project I had to work with. JSP pages that never failed. Never.

    All JSP were something like:

    <html> <% try { %> .... ... jsp .... <% } catch(Exception e) { } %> </html>

    random javascript not working, forms missing pieces, tables truncated were almost nearly the daily situation...

  • Malfist (unregistered)

    This is really sad, not only does it throw and catch it's own exception and then do nothing, it also casts the exteption upwards so you lose the data of what it was to begin with.

  • Malfist (unregistered)

    This is really sad, not only does it throw and catch it's own exception and then do nothing, it also casts the exteption upwards so you lose the data of what it was to begin with.

Leave a comment on “If At First You Don't Succeed”

Log In or post as a guest

Replying to comment #:

« Return to Article