CATCHING THE RIGHT EXCEPTIONS Dealing with Exceptions properly is a difficult balance to achieve, since they sometimes result in obscure program behaviors. However, there are three simple rules that you can follow to avoid the risks of poorly handled Exceptions. 1. Always catch the type of Exception being thrown and not a superclass. The following snippet of code is an example of what NOT to do: try { File file = new File("/tmp/somedir/some.file"); file.mkdirs(); } catch(Exception e) { e.printStackTrace(); } Instead, use the following style of code: try { File file = new File("/tmp/somedir/some.file"); file.mkdirs(); } catch(IOException ioe) { ioe.printStackTrace(); } To obey a common code convention, use the capital letters of the Exception class for the variable name, such as: catch(FileNotFoundException fnfe) and catch(SQLException sqle) 2. Never leave a catch block empty. Too often, try/catch blocks are written but nothing is done in the catch part of the block. Always print at least the stack trace, or if a Logging API is used, write the Exception to the Log. Here's an example of what NOT to do: try { File file = new File("/tmp/somedir/some.file"); file.mkdirs(); } catch(IOException ioe) { } Here's a proper example: try { File file = new File("/tmp/somedir/some.file"); file.mkdirs(); } catch(IOException ioe) { ioe.printStackTrace(); } 3. Never throw Exception. Developers should always create their own exceptions to throw. An API that throws Exception is very difficult to deal with. By declaring that a method throws java.lang.Exception, all the issues of problem number 1 are forced upon the API users, not allowing them to deal with Exceptions professionally. By declaring subclasses of Exception for the API to throw, the API developer makes the user's life much easier. ----------------------------------------