Java @ Desk: Exception handling | Java at your desk

Rethrowing Exceptions with More Inclusive Type Checking

Rethrowing Exceptions with More Inclusive Type Checking

With Java SE 7, you can throw more precise exception, i.e. you can actually throw an exception type which a try block can throw.

The exception thrown in the catch clause can be different than the one which is declared in the method signature.

Method declaration can throws more precise exception type.


Consider the following example

public static void invalidRethrow() throws Exception {
 try {
  URL url = new URL("invalidurl");
     BufferedReader reader = new BufferedReader(
      new InputStreamReader(url.openStream()));
     String line = reader.readLine();
     SimpleDateFormat format = new SimpleDateFormat("MM/DD/YY");
     Date date = format.parse(line);
 } catch (Exception e) {
  System.out.println("Caught exception: " + e.getMessage());
  throw e;
 }
} 


This examples's try block could throw either IOException or ParseException.

Suppose you want to specify these exception types in the throws clause of the invalidRethrow method declaration. It would have lead to compilation error because the exception parameter of catch clause is of type Exception. In releases prior to Java 7, you can only specify the exception type Exception in the throws clause of the invalidRethrow method declaration.

However, in Java 7, you can specify the exception types IOException and ParseException in the throws clause in the invalidRethrow method declaration. The Java 7 compiler can determine that the exception thrown by the statement throw e must have come from the try block, and the only exceptions thrown by the try block can be IOException and ParseException. Even though the exception parameter of the catch clause, e, is type Exception, the compiler can determine that it is an instance of either IOException or ParseException:

public static void invalidRethrow() throws IOException, ParseException {
 try {
  URL url = new URL("invalidurl");
     BufferedReader reader = new BufferedReader(
      new InputStreamReader(url.openStream()));
     String line = reader.readLine();
     SimpleDateFormat format = new SimpleDateFormat("MM/DD/YY");
     Date date = format.parse(line);
 } catch (Exception e) {
  System.out.println("Caught exception: " + e.getMessage());
  throw e;
 }
} 


Caught exception: no protocol: invalidurl
java.net.MalformedURLException: no protocol: invalidurl
 at java.net.URL.<init>(URL.java:585)
 at java.net.URL.<init>(URL.java:482)
 at java.net.URL.<init>(URL.java:431)
 at Exception.test.rethrowEx (test.java:61)
 at Exception.test.main(test.java:52)


The compiler verifies that the type of the rethrown exception meets the following conditions:

1. The try block is able to throw it. i.e. catch cannot throw any other exception which is not declared. It will give compilation error Unhandled exception type Exception
2. There are no other preceding catch blocks that can handle it.
3. It is a subtype or supertype of one of the catch clause's exception parameters.



Previously, you cannot throw an exception that is a supertype of one of the catch clause's exception parameters. A compiler from a release prior to Java SE 7 generates the error, "unreported exception Exception; must be caught or declared to be thrown" at the statement throw e.

The compiler checks if the type of the exception thrown is assignable to any of the types declared in the throws clause of the rethrowEx() method declaration.

However, the type of the catch parameter e is Exception, which is a supertype, not a subtype, of IOException and ParseException.

Note: You can use multi-catch here too in the catch clause to be more precise.

public static void rethrowEx() throws IOException, ParseException{
 try {
  URL url = new URL("invalidurl");
     BufferedReader reader = new BufferedReader(
      new InputStreamReader(url.openStream()));
     String line = reader.readLine();
     SimpleDateFormat format = new SimpleDateFormat("MM/DD/YY");
     Date date = format.parse(line);
 } catch (IOException | ParseException e) {
  System.out.println("Caught exception: " + e.getMessage());
  throw e;
 }
}


The exception handling changes in Java SE 7 allows you not only to write more crisp code by using its multi-catch feature but also allows you to let your bubble up your original exception by allowing you to re-throw it.

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

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.

Difference between checked and unchecked exception in java?



Checked exceptions are the ones that are checked at compile time. In order to proper compilation of the program, such exceptions need to be handled either using a try/catch block or using the throws clause.

Example : SQLException is a checked exception. If a code is trying to get the connection from database, then SQLException is the one that need to be handled for proper compilation of a program.


Difference between throw and throws in java

The throw keyword is used to force or throw an exception to the caller of the method. Throw keyword is used inside the method to throw any type of exception with the customized error message.

Throws keyword is used in the method declaration. Throws keyword actually throws that type of exception which is not handled by the method definition. For example, a method is doing some database connection and is not surrounded by try/catch block, so this method throws SQLException. The throws clause tells the compiler that this particular exception would be handled by the calling method.


Use of finally block in java

1) finally block comes in a combination of try-catch-finally or try-finally.
2) The code written in finally block will always gets executed even if the code in try or catch block fails to execute.
3) The importance of this block is to free out the resources if any.