Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java compile time checked exception

Exception and IOException both are compile time checked exceptions.

But, we cant use IOException within catch block. But we can use Exception within catch block what is the reason for it.

    import java.io.*;
    class Demo{
        public static void main(String args[]){
            try{

            }catch(IOException e){ // Does not compile

            }

            try{

            }catch(Exception e){ // Compile

            }
        }
    }
like image 628
Saveendra Ekanayake Avatar asked Jan 07 '23 14:01

Saveendra Ekanayake


1 Answers

You cannot catch a checked exception that is never thrown in a try block, except for Exception (or Throwable). This behavior is specified by the JLS, Section 11.2.3:

It is a compile-time error if a catch clause can catch checked exception class E1 and it is not the case that the try block corresponding to the catch clause can throw a checked exception class that is a subclass or superclass of E1, unless E1 is Exception or a superclass of Exception.

like image 109
rgettman Avatar answered Jan 19 '23 21:01

rgettman