Kumar Abhinav
Kumar Abhinav

Reputation: 6675

Behaviour difference in any checked Exception (except Exception )vs Exception

I believe that java.lang.Exception is also a checked exception.But there is difference in behaviour between java.lang.Exception vs any other checked exception such as IOException or SQLException.

See the following code compiled with Java version 7

 try {
    //empty try block   
    } catch (SQLException e) {

        e.printStackTrace();
    }

This gives the following comilation error:-

java.lang.Error: Unresolved compilation problem: Unreachable catch block for SQLException. This exception is never thrown from the try statement body

but the same code doesnt give any compilation error if there is no statement in try block:-

       try {
        // empty try block
    } catch (Exception e) {

        e.printStackTrace();
    }

*Result:- No compialtion error *

Upvotes: 0

Views: 140

Answers (2)

Prashant Thakkar
Prashant Thakkar

Reputation: 1403

SqlException is specific exception as compare to Exception which is generic. In case when you are trying to catch more specific exception, compiler would be checking the code in try to see if code can lead to that specific exception. But in case of Exception, it is generic and all the exception are child to Exception hence compiler ignores it as it is not specific to any particular piece of code....

I hope this helps..

Upvotes: 0

Seelenvirtuose
Seelenvirtuose

Reputation: 20628

The distinction between unchecked and checked exceptions is being made by "checking" whether the exception is a subtype of RuntimeException or not.

Additionally, RuntimeException itself is a subtype of Exception. So Exception covers all checked and all unchecked exceptions. So, in your code example, the compiler is not allowed to complain.

Upvotes: 2

Related Questions