- Feature Articles
- CodeSOD
- Error'd
- Forums
-
Other Articles
- Random Article
- Other Series
- Alex's Soapbox
- Announcements
- Best of…
- Best of Email
- Best of the Sidebar
- Bring Your Own Code
- Coded Smorgasbord
- Mandatory Fun Day
- Off Topic
- Representative Line
- News Roundup
- Editor's Soapbox
- Software on the Rocks
- Souvenir Potpourri
- Sponsor Post
- Tales from the Interview
- The Daily WTF: Live
- Virtudyne
Admin
I just want to say I'm glad I woke up early enough to be the first poster.
Admin
Wheeeee! Now i know one more useful way to handle exceptionzz! went modifying code in all progs
Admin
always a good way to start the day ...
Admin
Fire the idiot ... and throw them out the window
Admin
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)
Admin
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?
Admin
WOW! Look where he put the opening braces! (And don't get me started on the two column indent!)
Admin
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!
Admin
On Error Don't Do Anything Different
Admin
This almost goes one better than On Error Resume Next. This is: On Error Resume Error.
Admin
This guy is awarded, in my book, for exceeding other's low expectations.
Shine on you crazy diamond!
Admin
"On Next Resume Error" would be even better. The CPU would get, like, 3 feet of air. No need for the extra fan.
Admin
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
Admin
How about we name that scenario, "Mighty Morphing Power Exceptions"? [:D]
Admin
Wow, whodathunkit a "quote" button... errr ok, nevermind. My vote is still for "Mighty Morphing Power Exceptions"
Admin
try - catch - somebody-else's-problem (a.k.a. "hot potato" exception handling)
Admin
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!
Admin
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.
Admin
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
Admin
Because he was trying to show he WASNT lazy. He HAD to try...
Admin
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! ;)
Admin
p.p.s.
When I am not looking at a specific posting, my taskbar button says
The Daily WTF (null)
I like it!
Admin
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.
Admin
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.
Admin
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.
Admin
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:
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.
Admin
Too bad Java won't let you not handle exceptions.
Admin
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.
Admin
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");
}
}
Admin
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.
Admin
Defenestration is the only correct response to many a WTF nominated coder.
Admin
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!!!"));
}
}
Admin
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();
Admin
Instead of catching Exceptions, catch and rethrow Throwable so that you'll get the errors too.
Admin
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*
Admin
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
Admin
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:
It's really kind of depressing. :-(
Admin
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! :)
Admin
It's more of an exception mishandler really.
Admin
At least the exception is rethrown. How many times have I seen this in code...
try {
.... does something
} catch(Exception e) {
// do nothing
}
Admin
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.
Admin
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....
}
}
}
Admin
GET OUT OF MY HEAD!!! [:P]
Sheesh.... Where is my tin foil hat when I need it?
Admin
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.
Admin
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
Admin
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.
Admin
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....
Admin
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.
Admin
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?
Admin
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?