Sunday, July 31, 2011

Catch statement has modified implementation in JDK 7

Part of coin project is modified implementation of catch block. Now multiple exception can be catached in single catch block. We can use it in following way :

try {
String str = null;
int i = 12 / 0;
System.out.println("String length : " + str.length());
} catch(NullPointerException | ArithmeticException e) /*Multiple exceptions in a catch statement*/{
System.out.println("Exception occured : " + e.getMessage());
}

As seen in above code, two exceptions are mentioned in catch block and which ever exception will be occur that will be catch.
But we cannot mention exceptions which are related by subclassing in mutli catch statement.
For e.g.
try {
String str = null;
int i = 12 / 0;
System.out.println("String length : " + str.length());
} catch(NullPointerException | ArithmeticException | Exception e) /*Not allowed*/{
System.out.println("Exception occured : " + e.getMessage());
}

In above code, Exception is parent class of NullPointerException and ArithmeticException and so these cannot be mention in same multi-catch statement.

2 comments:

  1. Can you give some tips on how the behaviour of error class and exception class differs with some good examples.

    Thanks,
    Pranab

    ReplyDelete
  2. @Pranab
    Both error and exception class extends Throwable class.
    Error class represents problems which usually application should not try to catch. For e.g. OutofMemory error cannot be catch by application because it cannot be figure out properly due to which part of code it occurs.

    Exception class represents problems which occurs due to some improper handling of conditions and it should be catch by application so user can get proper message and handle such conditions properly for that part of code. For e.g. FileNotfound exception signifies file is missing in directory, ArrayIndexOutofbound exception signifies try to access out of range index of array.

    But catch block of try handles throwable class object and hence both error and exception class object can be catch. But for error object, its hard to signify when it will occur.

    ReplyDelete