19.6. Tower of Hanoi

 
[Page 590 ( continued )]

17.6. When to Use Exceptions

The try block contains the code that are executed in normal circumstances. The catch block contains the code that are executed in exceptional circumstances. Exception handling separates error-handling code from normal programming tasks , thus making programs easier to read and to modify. Be aware, however, that exception handling usually requires more time and resources because it requires instantiating a new exception object, rolling back the call stack, and propagating the exception through the chain of methods invoked to search for the handler.

An exception occurs in a method. If you want the exception to be processed by its caller, you should create an exception object and throw it. If you can handle the exception in the method where it occurs, there is no need to throw or use exceptions.

In general, common exceptions that may occur in multiple classes in a project are candidates for exception classes. Simple errors that may occur in individual methods are best handled locally without throwing exceptions.

When should you use a try-catch block in the code? Use it when you have to deal with unexpected error conditions. Do not use a try-catch block to deal with simple, expected situations. For example, the following code

   try   { System.out.println(refVar.toString()); } 

[Page 591]
   catch   (NullPointerException ex) { System.out.println(   "refVar is null"   ); } 

is better replaced by

   if   (refVar !=   null   ) System.out.println(refVar.toString());   else   System.out.println(   "refVar is null"   ); 

Which situations are exceptional and which are expected is sometimes difficult to decide. The point is not to abuse exception handling as a way to deal with a simple logic test.

 


Introduction to Java Programming-Comprehensive Version
Introduction to Java Programming-Comprehensive Version (6th Edition)
ISBN: B000ONFLUM
EAN: N/A
Year: 2004
Pages: 503

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net