Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding exception handling - Rethrowing exceptions

Tags:

java

exception

Consider the below code snippets

In code snippet 1, method m1() has SQLException in throws declaration, but it is actually throwing a reference variable of type Exception. I was expecting compiler error here, since Exception is not mentioned in the throws declaration. But it compiles and prints Caught successfully

import java.sql.SQLException;
public class Snippet1{
    private static void m() throws SQLException{
        try{
            throw new SQLException();
        } catch(Exception e){
            throw e;
        }
    }

    public static void main(String[] args){
        try{
            m();
        } catch(SQLException e){
            System.out.println("Caught successfully"); //prints "Caught successfully
        }
    }
}

Code snippet 2 is almost same as the previous one, except that we assigned null to the exception reference variable e and then throw it. Now the compiler complains that Exception must be caught or declared to be thrown.

import java.sql.SQLException;
public class Snippet2{
    private static void m() throws SQLException{
        try{
            throw new SQLException();
        } catch(Exception e){
            e = null;
            throw e;
        }
    }

    public static void main(String[] args){
        try{
            m();
        } catch(SQLException e){
            System.out.println("Caught successfully");
        }
    }
}

I do not understand why #1 compiles and #2 doesn't.

like image 999
Siva Avatar asked Feb 11 '26 02:02

Siva


1 Answers

This is described in JDK 7 Rethrowing Exceptions with More Inclusive Type Checking

public void rethrowException(String exceptionName)
 throws FirstException, SecondException {
   try {
     // ...
   }
   catch (Exception e) {
     throw e;
   }
 }

The Java SE 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 FirstException and SecondException. Even though the exception parameter of the catch clause, e, is type Exception, the compiler can determine that it is an instance of either FirstException or SecondException

This analysis is disabled if the catch parameter is assigned to another value in the catch block. However, if the catch parameter is assigned to another value, you must specify the exception type Exception in the throws clause of the method declaration.

like image 149
Lesiak Avatar answered Feb 16 '26 09:02

Lesiak