Sunday, March 6, 2011

Simple Java Exception Handling Tips

Exceptions are errors that occur in runtime , that is , when the application is running.

A careful developer should estimate and care about possible runtime errors.

Let us give an example :

String s = args[0];
int i = Integer.parseInt(s);

this piece of code can cause some exceptions. For example args is an array of string. We want to read the first element of this array. What happens if args is null ? What happens if args is empty ?

so we need to ensure that the array is not null and not empty.

  1.         String s = null; // initialize s
  2.         // check the array is not null or empty
  3.         if (args != null && args.length > 0)
  4.             s = args[0];
  5.         int i = 0;
  6.         if (s != null) // if s is not null we can parse
  7.             i = Integer.parseInt(s);
  8.         else { // s is null , so show an error message and exit
  9.             System.err.println(
  10.             "Invalid argument , should be a valid integer value" );
  11.             System.exit(1);
  12.         }
  13.        
  14.         System.out.println("square of "+i+" is ="+(i*i));

But there is still a possible cause of exception. We here assume that if s is not null than s contains an integer value that can be parsed without an error. But assumptions always cause exceptions. String s can be a "hello world" string and parseInt fails with this value.

so we need to rewrite our code :
  1.         String s = null; //initialize s
  2.  
  3.         if ( args != null && args.length > 0 )  //check the argument array is null or empty
  4.             s = args[0];
  5.            
  6.         int i = 0 ;
  7.  
  8.         if ( s != null )  { //if s is not null we can try to  parse
  9.                
  10.             try {
  11.                 i = Integer.parseInt(s);
  12.             } catch (NumberFormatException e) {
  13.                 e.printStackTrace(); //dump the error
  14.                 System.err.println("Invalid argument , should be a valid integer value");
  15.                 System.exit(1);
  16.             }
  17.                
  18.             }
  19.         else { // s is null , so show an error message and exit
  20.                 System.err.println("Invalid argument , should be a valid integer value");
  21.                 System.exit(1);
  22.             }  
  23.        
  24.         System.out.println("square of "+i+" is ="+(i*i));

as an alternative to try/catch blocks we can declare our methods as it throws exception , for example :

  1.     public int square(String s) throws NumberFormatException {


No comments: