Exceptions Indicate Bugs

Too often you will see something like this:

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

Don't do this. A "catch (Exception)" command will pick up every exception, not just the ones you know can't happen or aren't worth caring about. Most notably, it will catch and silently ignore NullPointerException and ClassCastException, which are generally more indicative of problems in your code than of exceptional runtime circumstances. Obviously, you've declared that the show can go on in the event of a failure in the try block, so this won't cause an immediate problem, but you'll be deprived of error feedback.

Therefore,

Identify the exceptions which would generally only be thrown in the event of a bug in your code (most RuntimeExceptions fit this bill). Don't explicitly catch these exceptions (unless you intend to use them to warn the user of a bug in the program). Wherever you catch "Exception", do not leave the catch block empty - add code to handle bug-indicator exceptions differently. If you have logging routines, be sure to log the exceptions that occur even if you do nothing else with them. If not, then write some custom debugging static method to handle Exceptions, check that they are not runtime exceptions - and if they are, to (possibly) rethrow them.

 public static void genericHandleException(Throwable t)
 {
	 if (t instanceof RuntimeException) {
		 throw (RuntimeException) t;
		 // t's stacktrace will show where it was created, will not mention this method
	 }
 }

Edited by KarlKnechtel. I'm not sure I agree with that last bit of advice, actually...

I general I do not agree either, but I have often seen code like this:

 try
 {
   f();
 } catch (RuntimeException e) { throw e; 
 } catch (Exception e) { log("ignored due to <x>");
 }

and this can be summarized to

 try
 {
   f();
 } catch (Exception e) { ignoreCheckedException("<x>"); 
 }

with the above approach (sufficiently renamed and logging added). Not that this kind of error handling and logging is the best, but at least it can be improved/refactored this way. -- .gz


See also EmptyCatchClause, DontCatchRuntimeExceptions


CategoryException

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