10 best practices with ExceptionsFrom WikiJavabuy this book
This article enumerates ten best practices to adopt when you are programming in Java and you are using An exception is an event that breaks the normal flow of the program. Any event may be an exception, but in Java we normally use exceptions when errors happen. For this reason we normally refer to exceptions as to the error handling system of Java. This article will assume some basic knowledge about the exceptions and will attempt to provide guidelines on how to best use them. If you find it hard to read this article refer to the tutorial about exceptions from Sun, which gives a good basics on this topic.
RelevancyA method can only throw the exceptions that are relevant to its interface. For example see the constructor: java.io.FileInputStream.FileInputStream(String name) throws FileNotFoundException Which opens a file on the disk for reading bytes. It makes sense that this constructor throws a So keep the exceptions you throw relevant to the interface. EncapsulationTo follow the principle of relevancy it may be useful the trick of encapsulating exceptions one into another. For example if your method is throwing an exception received from another method (which is a very common scenario) it should encapsulate it in a locally generated Exception class. Like it's shown in the example: try { return new FileOutputStream(fileName); } catch (FileNotFoundException e) { throw new ActionException(e); } The method receives an Exception generated by the The method that catches this exception can at any time get the information about the If you print the stack trace you will see a list of ReasonThe exceptions must always say what caused them. There are two viable approaches:
The first approach allows you to write different code for handling the different events, but it requires you to write lot of Exception classes and in some case it could be just too much. The second approach is more concise, but it makes it difficult to handle the different situations. As it happens very often in programming the best solution is in the middle, where you balance generating separate exceptions and using one exception for other cases. The rule of the thumb in this case could be to generate a separate Exception class for the exceptions you want to handle specifically with separate code, while use a single generic Exception class for exceptions you want to treat in a default way, for example you just want to bubble them up the stack trace to show an error message. Exception namesThe names of the exceptions should always be meaningful and must express what happened that caused them.
For example My approach is that whenever I feel like throwing For example, if I am writing the
We used this principle in the example mentioned above (repeated here): try { return new FileOutputStream(fileName); } catch (FileNotFoundException e) { throw new ActionException(e); }
package org.wikijava.network.batBot.delegates.interfaces; public class ActionException extends Exception { public ActionException() { // TODO Auto-generated constructor stub } public ActionException(String message) { super(message); // TODO Auto-generated constructor stub } public ActionException(Throwable cause) { super(cause); // TODO Auto-generated constructor stub } public ActionException(String message, Throwable cause) { super(message, cause); // TODO Auto-generated constructor stub } } This class was completely automatically generated by Eclipse. Note that It contains only the four constructors. All the other methods are inherited from Balance what you catchSimilarly to the reason principle not only we can decide what to throw, we have control also on what to catch. We can use two approaches for our catch blocks:
} catch (Throwable e) { throw new CommandExecutorException(e); }
} catch (ClassCastException e1) { ... } catch (FileNotFoundException e) { ... } catch (IOException e) { ... } The first approach is very compact but basically groups every exception in the same case, it's useful only in the situation where all the exceptions are managed equally and do the same thing, for example they bubble up to the view and become a message to the user. This approach is generally discouraged as it gives no control on the exceptions being catched, leading sometimes to tough bugs, which are also hard to find. The second approach requires more lines of code but you can execute different operations depending on the exception occurred. This approach is more flexible but in some cases leads your methods to be very long due to exception handling. This is normally the most accepted way of catching exceptions. If you use properly the encapsulation, relevancy and the Scoping principles you should already mitigate a lot this problem, and you should not have too long series of catch blocks. ScopingHow long should a If you write too few Once again the best solution is in the middle. Try to use
If you balance the dimension of your Use FinallyVery often Programmers forgot about the finally block that you can attach to the try catch blocks. The you can see it in action in the following example (from Split File : FileWriter output= null; try { output = new FileWriter(file); output.write(stringBuffer.toString()); System.out.println("file " + path + filename + " written"); } catch (IOException e) { e.printStackTrace(); } finally { try { output.close(); } catch (Throwable e) { e.printStackTrace(); } } The side effect is that very often you end up needing to nest try&catch blocks within the finally blocks. There's a danger here because you could write: try { output.close(); } catch (IOException e) { e.printStackTrace(); } but this would collide with the Throw only ExceptionsIn Java you can throw just anything, you are not bound to throw Exceptions. If you create your own class and extend the Throw early catch lateThis is probably the most famous principle about Exception handling. It basically says that you should throw an exception as soon as you can and catch it late, wait until you have all the information to handle it properly. This principle implicitly says that you will be more likely to throw it in the low level methods, where you will be checking if single values are null or not appropriate. And you will be making the exception climb the stack trace for quite several levels until you reach a sufficient level of abstraction to be able to handle the problem. Ultimately you may reach the GUI to ask the user what to do, or even to the main, and manage a neat exit of the program. Add validationAt some points in your application you know what to expect, and you generally assume that your inputs are correct. It's sometimes a good idea to to double check your inputs, to make sure that they are what you expect and throwing and exception if they are not. This is useful because it makes obvious by reading the code what you expect at specific points, so it increases the readability, plus it create some fixed points that alert you if during the execution something went wrong. For example a validation I do quite often is similar to the following: if ( null == variable || variable.isEmpty()){ throw new blahException("the variable cannot be null at this point"); } It's not necessary to be maniac about this, and clutter your code with variable validations. A good rule I follow is to add these validations whenever I'm solving a bug, in this way if the bug gets introduced again, I can spot it quickly.
|

Thx for this article, very interesting !
Jmix from http://lexique-du-net.com/blog/
--193.54.225.89 12:04, 14 January 2009 (UTC)