Log In
E-mail or User ID
  Keep me signed in
Recover Password
Create an Account

Always Forward Exceptions. Period.

Repeat after me, "I will always forward exceptions so the caller of my code knows why it broke. I will always forward exceptions so the caller of my code knows why it broke. I will always forward exceptions so the caller of my code knows why it broke."

Let say that you are hypothetically working with a VERY expensive Java based charting product. You've hypothetically been experiencing exceptions in code that are so vague as to be pointless. The hypothetical code is not compiled with debugging information, so you have no way of figuring out what's going one.

But let's hypothesize that the code is actually returning an IOException when it can't parse an XML Document. And let's hypothesize that this IOException is being thrown in a catch block for Exception. Now, let's hypothesize that the original Exception is not output to the logger and it is not set as the cause of the IOException. I know, it's hard to hypothesize something like that.

Now, let's hypothesize that to figure this crap out that you have to find a Java decompiler and spend many hours tracing through spaghetti methods named a, b, c, d, and e, each of which has numerous overloads.

Let's hypothesize that with a single line of code could have saved you over 12 hours of debugging:

System.out.println(e.getMessage()); e.printStackTrace(); throw e;

I know, it's hard to hypothesize something like that, but try. It really does happen to people. It really makes people angry. It really puts people very behind schedule. It really makes people tell everyone that iLog JViews Charts 7.5 is garbage, hypothetically speaking.

Read 9 comments


It's unwise to catch Exception, as then you don't get alerted by the compiler to new exception types that you might want to handle in better ways. Also, you unwittingly end up catching RuntimeExceptions, which you don't want to. If you catch it, log it and then rethrow it, you're polluting the logs - imagine if every level did that; you'd have possibly 20 traces for one exception. Log it, handle it (if it's an expected exception) or rethrow it as a RuntimeException. Doing two or more of those is broken.
There are many time that catching an exception is necessary, especially in Java when you code that is made up of pre-Throwable and post-Throwable. In the pre-Throwable world you had to declare every exception your code made throw, which is horroble. Many developers just starting puting "throws Exception" on everything. Yuck. With Throwable, you don't have to do that, but if your newer, Throwable-enabled code calls code based on java.lang.Exception, then you have to convert from Exception to Throwable at some point the keep from declaring "throws Exception" on every method. This is where things got hypothetically nasty last night. Somebody decided to make that transition, but not log or incorporate any information from the original exception anywhere. They simply returned null and expected a method further up the call stack to interpret that as a failure and start a new Throwable chain. Hypothetically speaking, of course. I wouldn't actually know because I wouldn't actually decompile a vendor's code. Also, you can use Throwable chaining to your advantage. Java 5 gives you generics which allows you to create a great self-logging Throwable mechanism like the one I use for .Net.
When I said 'catch Exception', I meant specifically the class java.lang.Exception, not catching exceptions in general. Converting exceptions to be Throwables is also a bad idea, RuntimeException exists for that; you don't have to catch-or-specify a RuntimeException. "Many developers just starting puting "throws Exception" on everything." Yes, that's a problem, but catch (Exception e) doesn't fix it, it just hides the problem. It's better to catch individual subclasses of Exception, that way you don't end up handling the same exception many times. You're correct, null is an awful way to deal with problems, just as any error code is. I detail a smarter way to return null on my blog.
Im not sure i agree with you on your first post. The design of the exception mechanism is to be able to defer handling of exceptions in order to let the method that knows how to handle the exception can take measures to fix/report the problem. Lets say you are making components for other people to use. You have a desicon to make, what kind of actions can the users of your code take in order to fix the problem, and do you want them to have to care about the inner workings of your classes? Encapsulation helps shield the users from your code, and this is true for exceptions as well. Exceptions like IOExceptions isnt very useful unless you have an understanding of the code in question. If you catch this exception, you are able to piggy-back specific information that is relevant for the exception. Instead of throwing an IOException to the user, you can throw a "PropertyFileNotFoundException" that is far more useful to the users of your code. As i stated earlier, it is all a question of how your classes are supposed to be used.
I have a much simpler philosophy for Exception. Either deal with it completely or Don't catch it at all. Way too often I see code like this: try { // blah blah blah } catch(Exception e) { Log(e); throw; } The Log(e), as pointed out above, just pollutes the log file. THe rest spends a lot of cycles doing nothing. The whole thing should have just been reduced to : // blah blah blah Allowing any exception to bubble up to a level where they know how to deal with it.
@James, The problem I have with that approach is that you get zero feedback from the call stack on what's wrong with the application. Please take a look at the link I posted about Improving Exception Handling with Reflection and Generics. It may change your mind.
We have to distinguish checked exceptions from unchecked ones. Checked exceptions must be forwarded until an appropriate measure is taken - provided one is possible, of course. There shouldn't be several stages of handlers for a specific exception. The only handler where the checked exception is caught is the right place to log something, with or without the stack trace depending on the context needed to understand where, why, and/or how. Log line should be written before execution of the exception handling code, as itself can fail.

As said by someone above, there's no need to log an exception more than once. If there's really "nothing to do", it's time either to trash the exception (at least with a log line), or to wrap it into a runtime exception, that will be managed more globally (let's say an automated error report sent to your company).

Remember (or learn) the "Zen of Python" by Tim Peters: one of the mantras is "Errors should never pass silently", followed by another one: "Unless explicitly silenced."

Correct me if I'm wrong.

This is a post about a Java problem on a Visual Basic .NET forum?

I'm trying to something like this:

method xxx throws exception { ... }

But in VB.NET and have found nothing up to now on how to do that. It won't allow me to throw the exceptions to the caller, they're always catched by the debugging system on the method itself :(

I cover Java as well as .Net on this blog, but more-so with .Net. Java allows exception declaration for each method so that it forces callers of that method to catch those exceptions. There's hot religious debate about the value of this and in later versions of Java this requirement was dropped and Java now allows both declared and undeclared exceptions to be thrown.

From the VB.Net perspective, throwing an exception and it always being caught by the debugger is a sign that you are running your code on a system with the .Net Framework SDK installed and the debugging service running. If you want your exception to not be triggered into the debugger then you should remove the .pdb file from the binary directory, or simple rebuild your application using the Release profile.

Leave a Comment

Connect to this blog to be notified of new entries.
You are not logged in.
Sign In to post unmoderated comments.
Join the community to create your free profile today.
Archive Category: Code Techniques
Keyword Tags:  Exceptions   Java   Best Practices

Receive the latest blog posts:
Share Your Perspective
Stuff, Feeds & Stats

Performancing Metrics Blog Statistics