Dont Catch Runtime Exceptions

The annoying thing in the JavaLanguage is that RuntimeException is a subclass of Exception, which means that

try {
...
} catch (Exception e) {

this catches runtime exceptions }

The appropriate way to do this is probably

try {
...
} catch (RuntimeException e ) {

throw e; } catch (Exception e) {

this catches runtime exceptions }

...or to catch the exceptions in the try block individually. --JeanPhilippeBelanger

IMHO the answer to this is CatchSpecificExceptions?. You shouldn't be catching Exception; methods shouldn't throw Exception. I find that catching Exception is sort of like using empty catch blocks: it often shows that the exception that is occurring is not being handled properly. In this case it is being handled too generically (as a generic Exception instead of the actual Exception type that was thrown). I really can't think of a good reason to catch a RuntimeException subclass. -- IainLowe

My interpretation of "catch (Exception e)" has always been "if anything goes wrong", so there would be valid reasons for using them, except that catching them often means "if anything goes wrong OR if I've made a programming error". I'd like to see the programming errors. -- JeanPhilippeBelanger

Should this page be renamed DontAccidentallyCatchRuntimeExceptions?? The advice given (catch Exception will catch runtime exceptions), but there are cases when catching a runtime exception is valid. For example you might want to check for security exceptions.

There are even times when catch (Throwable) is good - for example if you are writing a JSP engine or EJB engine you want to trap any errors in the client code when you call a method. --Anonymous

Common practice for handling runtime exception is to let the container do it, namely defining a runtime exception error page in deployment descriptor and let that page lead user to support desk (servlet 2.3 passes the exception object to the JSP page). Runtime exceptions are usually not recoverable, so let client code to handle the exceptions does not make a lot of sense (what can it do?). -Jian

But this is the exception, not the rule. I agree that this is a breakeable rule. It seems to me that people who never break rules don't really understand them. -- JeanPhilippeBelanger

Usually when I see catch (Exception e) it means that the person who wrote the code is not really sure what exception is thrown in the corresponding try block. I agree that there are situations where you explicitly want to catch a certain generic exception (as in the example above), however I believe that in the majority of cases it is better to CatchSpecificExceptions? and DontCatchRuntimeExceptions. -- IainLowe


What's the rationale for treating RuntimeExceptions differently? Doing so bloats the code with adding any obvious value.

The rationale is, some RuntimeExceptions? are thrown by the VM for arbitrary reasons (like running out of memory, or stack space). You didn't intend to catch a StackOverflowError?, did you? With that empty catch block? Especially since several real-world VMs tend to get unstable on stack overflow. Bottom line: unless you really know what you're doing and why, DontCatchRuntimeExceptions.


In C++, the standard way to catch "all exceptions" is this:

 try {
foo();
 } catch (...) {
handle_exception();
 }

In Microsoft Visual C++, there is an additional twist: in addition to catching thrown C++ exceptions, a catch(...) will also catch system exceptions, such as access violations, divide-by-zero, etc. So if foo() in the above example "crashes", the catch will cause handle_exception() to be called and the program will just keep on running.

This may be the behavior you want, but usually you don't. So don't use catch(...) in Microsoft Visual C++ programs; CatchSpecificExceptions? instead.


Catching generic exceptions could be useful when 1. The part of the code is the terminal execution point. i.e., if exceptions are not caught here, the client will see it. So you might want to catch it and show that this exception can not be recovered from and he might have to do something about it BUT in a user friendly way and NOT as stack trace (it should go into log and not on user's face!). 2. You want to wrap all the exceptions into your own exception class because it does something special. The you might have

try{
}
catch (Exception e) {
throw new MyException("Message", e);
}
-- VhIndukumar


When am I allowed to catch a NullPointerException? At the moment we're writing lots of code in AtgDynamo, dealing with dodgy data. Our current development cycle looks like: run the process, watch it crash because of dodgy data, clean up the data / handle the exceptional case in the code, recompile, restart Dynamo, start again. This is a problem when the "restart Dynamo, run the process" step takes about 45 minutes.

So here's an example of what I want to do:

try {
Map someProperties = (Map)pItem.getPropertyValue("someProperties");
String randomToken = AppUtil.getToken(getManager().getSomeOtherToken());
RepositoryItem tokenSpecificProperties = (RepositoryItem)assetInfos.get(randomToken);
List listOfBlah = (List)tokenSpecificProperties.getPropertyValue("someList");
for (Iterator i = listOfBlah.iterator(); i.hasNext();) {
RepositoryItem blah = (RepositoryItem)i.next();
// now do something with each blah
// the point being, there's a long chain of references, each of which could
// return null because of ATG's bogus API design. If I explicitly checked each
// one, the intention of the code would be so polluted by if (blah == null)
// etc, that it would be impossible to see what was going on. 
}
} catch (NullPointerException e) {
if (isLoggingError()) {
logError("Item " + pItem + " has dodgy data: someProperties = " + someProperties
+ ", randomToken = " + randomToken); // etc.
}
}

So I'm logging the errors as such (and if it is bad data, I can see this and go and fix it), but the whole process at least runs without crashing -- and the null pointer exceptions are really things we can comfortably recover from. Is this kosher? -- RobertAtkins

Sometimes: RulesAreMadeToBeBroken -- DaveOrme

Redundant with ExceptionsIndicateBugs?


CategoryJava | CategoryException


EditText of this page (last edited June 11, 2005) or FindPage with title or text search