Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need authoritative source for why you shouldn't throw or catch java.lang.Exception

I've got a coding standards meeting in just over an hour and I need a quick answer to this one.

Common wisdom among experienced Java programmers is that you don't throw or catch java.lang.Exception (with rare exceptions - no pun intended). The reason you don't do this is that the statement

catch (java.lang.Exception ex) {...}

will also catch unchecked Exceptions, and in most cases this is not what is intended.

We already have a lot of legacy code written by existing team members where they catch a subclass of java.lang.Exception, log an error, and rethrow the subclass as java.lang.Exception.

I need to convince them that

  1. They need to stop writing code like this.
  2. Existing code that uses this anti-pattern needs to be fixed

Number 2 means a fair amount of refactoring.

It will shorten the argument at the meeting if I can show an article or blog entry by one of the Java community heavyweights that makes this point (i.e. Joshua Bloch, James Gosling). My google-fu hasn't turned up anything so far.

Does anyone know of an article or blog by a respected Java guru that says that you shouldn't throw or catch java.lang.Exception?

Quick answers are much appreciated.

Dean

like image 575
Dean Schulze Avatar asked Oct 16 '09 14:10

Dean Schulze


2 Answers

Here's something: Java Tip 134: When catching exceptions, don't cast your net too wide (JavaWorld)

Effective Java (Second Edition) by Joshua Bloch might have something on this in Chapter 9 (Exceptions), although I couldn't quickly find anything about not catching Exception.

Here is a Q&A from JavaWorld about the question (also points to Java Tip 134) - it also explains why you sometimes have to break the rule of not catching Exception or even Throwable.

like image 176
Jesper Avatar answered Sep 27 '22 18:09

Jesper


See this article from Brian Goetz (the concurrency wizard) who has his own insight as well as quoting Josh Bloch in Effective Java

like image 32
Kevin Avatar answered Sep 27 '22 19:09

Kevin