Java SE 7 Exception Handling - Java @ Desk

Monday, August 18, 2014

Java SE 7 Exception Handling

Java SE 7 Exception Handling

Multi-Catch Exceptions

Multi- catch has been added to reduce the redundant code, to make the code more concise and clear. Moreover, it makes the exception handling easier.

Consider below example. Assume that you have bind the parameter and create a in your application. This class holds a value that can be used in a JDBC statement. This will ensure that your values get converted correctly and stored properly in the underlying DB.

public static Parameter getParameter(String fieldType,  String fieldValue){          
 try {
  // Code goes here
 } catch (ParseException ne){
  throw new RuntimeException("Error formatting for field: " +  "=" + fieldValue, ne);
 } catch (NumberFormatException ne){
  throw new RuntimeException("Error formatting for field: " +  "=" + fieldValue, ne);
 } catch (IllegalArgumentException iae){
  throw new RuntimeException("Error formatting for field: " +  "=" + fieldValue, iae);   
 }
 return p;
}


If you wanted to have the same logic for two of the three cases above, say, the ParseException and the IOException, you had to copy and paste the same code.

Unless you are lazy programmer to code as shown below:

public static Parameter getParameter(String fieldType,  String fieldValue) {
        try {
  // Code goes here
        } catch(Exception e){
  throw new RuntimeException("Error formatting for field: " +  "=" + fieldValue, e);
 }
        return p;
}


Any code in the try block could throw an exception that would be swallowed up with a blanket (Exception) catch clause. If an exception that is not a ParseException or IllegalArgumentException is thrown (for example, a IOException, LoginException), the code would still catch it, but the upstream user would not be aware of what really happened.

Swallowing up an exception like that makes problems difficult to debug. Below example shows how to properly combine the two statements into one catch block. Notice the syntax for the catch clause (NumberFormatException | IllegalArgumentException). This catch clause will catch both NumberFormatException and IllegalArgumentException.

So, now we can share the same exception handling code for two different exceptions you can use the pipe syntax as shown below:

Syntax: 
(ExceptionType| ... | ExceptionType variable).


public static Parameter  getParameter(String fieldType,  String fieldValue) {
        try {
 } catch (ParseException | IllegalArgumentException  ne){
  throw new RuntimeException("Error formatting for field: " +  "=" + fieldValue, ne);
 }
 return p;
}


If you notice in the above code, you are missing a catch for NumberFormatException, to answer this. We would have to understand how multi-catch works. Since NumberFormatException extends IllegalArgumentException , it cannot be catch at the same level of hierarchy i.e all the subtypes of particular exception is taken care of if you specify the exception. It is implied that Exception cannot be piped with i.e catch(Exception | ParseException e) will give compilation error.

Each alternative in a multi-catch clause must be able to catch some exception class thrown by the try block and uncaught by previous catch clauses. The second catch (Sub Class of First Catch) clause would cause a compile-time error because exception analysis determines that it is already caught by the first catch clause.

Now if we re-look at the syntax of multicatch exception



catch ( [VariableModifiers] CatchType |  CatchType  VariableDeclaratorId)   
Block


To summarize here are few pointer.

1. A catch clause has exactly one parameter, which is called an exception parameter.
2. An exception parameter may denote its type as either a single class type or a union of two or more class types (called alternatives). The alternatives of a union are syntactically separated by |
3. A catch clause whose exception parameter is denoted as a union of types is called a multi-catch clause.
4. An exception parameter of a multi-catch clause is implicitly declared final if it is not explicitly declared final.
5. Exception handlers are considered in left-to-right order: the earliest possible catch clause accepts the exception, receiving as its argument the thrown exception object.
6. A multi-catch clause can be thought of as a sequence of uni-catch clauses. That is, a catch clause whose exception parameter type is denoted as a union D1|D2|...|Dn is equivalent to a sequence of n catch clauses whose exception parameters have class types D1, D2, ..., Dn, respectively.

For example, the following code:

try {
}
catch (ClassNotFoundException | IllegalAccessException ex) {
    body
}


is semantically equivalent to the following code:

try {
} catch (final ClassNotFoundException ex1) {
    body
} catch (final IllegalAccessException ex2) {
    body 
}


whereby the multi-catch clause with two alternatives has been translated into two separate catch clauses, one for each alternative. A Java compiler is neither required nor recommended to compile a multi-catch clause by duplicating code in this manner, since it is possible to represent the multi-catch clause in a class file without duplication.

This post is written by Dipika Mulchandani. She is a freelance writer, loves to explore latest features in Java technology.





No comments:

Post a Comment