- 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
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?
Admin
Sorry for the double post.
Admin
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.
Admin
[: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!
Admin
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
Admin
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 {}
Admin
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
Admin
Whoops, I mean:
catch (Throwable t) {}
which is the most generic Java catch.
Admin
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.
Admin
Sure it could:
public class SQLException extends RuntimeException
{
...
Of course it's debatable whether this would really be have been better.
Admin
I know, but that's so ridicoulus I hesitated to mention it ;-)
Admin
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"?
Admin
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.>
Admin
20 Points to Alex. Brillant!!!!
Admin
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) {}
}
Admin
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.
Admin
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).
Admin
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....
Admin
You know it is almost impossible to add a keyword. Even this one. So why not to remove it simply?
Same semantic. Catch them all.
<font size="2">PS: Of course, I don't recommend it</font>Admin
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!
Admin
You mean like
<font size="2"> on error resume next</font>
?
It is sometimes useful.
Sincerely,
Gene Wirchenko
Admin
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.
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 ;-)
Admin
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.
Admin
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
Admin
I'm not an expert in C#, but wouldn't
this.load(FileName);
alone do exactly the same?
Admin
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
Admin
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.
Admin
That's not 'not handling' it. See how the main method 'throws Exception'?
Admin
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.
Admin
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.
Admin
No. The error status is set. That can be checked. Sometimes, it is enough.
Sincerely,This is not usually the case, but every so often, it is.
Gene Wirchenko
Admin
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.
Admin
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.
Admin
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));
}
}
Admin
Yes, and therein lies the WTF. They are functionaly equivalent except the one with the catch and rethrow is more code and executes slower.
Admin
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));
}
}
Admin
Never heard of
?
Admin
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) {};
Admin
Sounds like a fun game to me. I used to do it with balls. I wonder if it's the same with errors?
Admin
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.
Admin
try connection.close();
If that syntax would work, it would be great.
Admin
Of course! Silly mistake on my part ;-)
Admin
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?
Admin
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.
Admin
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.
Admin
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.
Admin
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.
Admin
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?
Admin
Well, how DO you "bar" concurrency issues? There's a number of security-creitical exploits that hinge on exactly that issue.
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.
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.
And we all have 100% test coverage. Yeah, sure...
Admin
OTOH the above isn't even a nice-sounding argument, it's no argument at all.
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?