Throw Sub-Exception, catch as Super Exception and re-throw it but declare throws Sub-Exception

Siddappa Walake :

Java docs explains clearly about object coherency while dealing with type-casting,return type of Over-riding method and throwing and catching Exceptions. But now i am little confused with Exceptions, What is the hidden concept behind this code..

void getNames() throws SQLClientInfoException { /*throws Subclass object to caller*/
    try{
        // throwing Subclass object to catch block but up-casting to Exception
        throw new SQLClientInfoException(); 
    } catch (Exception e) {
        throw e; /* re-throwing throwing as Exception 
    }
}
prasad_ :

Its a feature of programming language introduced in Java SE 7 - Use more precise re-throw in exceptions.

The Java SE 7 compiler performs more precise analysis of re-thrown exceptions than earlier releases of Java. This enables to specify more specific exception types in the throws clause of a method declaration.

Prior to Java 7:

void aMethod() throws CustomDbException {
    try {
        // code that throws SQLException
    }
    catch(SQLException ex) {
        throw new CustomDbException();
    }
}
  • Re-throwing an exception in the catch block need not indicate the actual exceptions possible from the try block.
  • The type of exception thrown could not be changed without changing the method signature.

In Java 7 or higher:

void aMethod() throws IOException {
    try {
        Files.copy(srcePath, trgtPath); // throws IOException
    }
    catch(Exception ex) {
        throw ex;
    }
}

The above code is legal in Java 7.

  • If an exception of some type is thrown in the try clause and is not assigned an exception variable in the catch clause, the compiler will copy over the checked exception type that can be thrown from the try block. (It is as if throwing all the exceptions possible from the try block provided that the exception variable is not reassigned).
  • The compiler knows that the only possible exception type is an IOException (because that is what the Files.copy() can throw).

Also, see this article at Oracle's website: Rethrowing Exceptions with More Inclusive Type Checking.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=161105&siteId=1