In this section, you will learn about the Java SE 7 exception rethrowing with improved type checking.

Exceptions Rethrowing with Improved Type Checking
In this section, you will learn about the Java SE 7 exception rethrowing with improved type checking.
Take a a look at the following code having improved type checking of Java SE 7 :
Two classes FirstException and SecondException is given below :
static class FirstException extends Exception { }
static class SecondException extends Exception { }
The third class, containing improved type checking, which have the following method :
public void rethrowException(String exceptionName)
throws FirstException, SecondException {
try {
if (exceptionName.equals("First")) {
throw new FirstException();
} else {
throw new SecondException();
}
}
catch (Exception e) {
throw e;
}
}
The above code will only execute using Java SE 7 , If you will try to execute
it through prior version than Java 7, you will get the error " unreported
exception Exception; must be caught or declared
to be thrown " .
The reason behind this is - the type of the catch parameter e is
Exception, which is a supertype, not a subtype, of
FirstException and SecondException. Throws must be like this
: "throws Exception" to compile the above code prior to Java 7.
But now(in Java SE 7), you can throw an exception that is a supertype of the throws type. Here Exception is the super type of the FirstException and SecondException.
The complete Code is given below :
import java.io.*;
public class J7RethrowingException {
public void rethrowException(String exceptionName)
throws FirstException, SecondException {
try {
if (exceptionName.equals("First")) {
System.out.println("FirstException is thrown");
throw new FirstException();
} else {
System.out.println("SecondException is thrown");
throw new SecondException();
}
}
catch (Exception e) {
throw e;
}
}
public static void main(String args[])throws FirstException, SecondException{
new J7RethrowingException().rethrowException("First");
}
}
OUTPUT
| C:\Program Files\Java\jdk1.7.0\bin>javac
J7RethrowingException.java C:\Program Files\Java\jdk1.7.0\bin>java J7RethrowingException FirstException is thrown Exception in thread "main" FirstException at J7RethrowingException.rethrowException(J7RethrowingException.java:9) at J7RethrowingException.main(J7RethrowingException.java:21) |