2017  Kodetalk | Feedback | Privacy Policy | Terms | About
userimage

Java exceptions which is exceptionally arcane

import java.io.IOException;

public class Exception1 {
    public static void main(String[] args){
        try{
            System.out.println("IOException man");
        } catch(IOException e){
            System.out.println("Seriously, This could happen man.");
        }
    }
}


The above program is speaking of the basic principle of java checked exception. If we look into the the program, then people may think that this program will compile and execute perfectly. Well that"s not entirely true. The above program won"t compile as the catch block will expect that code written inside try block will throw IOException, which is nothing but a checked exception. But the statement we have written don"t throw IOException. So at compile time compile will check the statement inside try is throwing any IOException or not, if not then will not compile.

The language specification says compile-time error for catch clause to catch a checked exception type E if the corresponding try clause can"t throw an exception of some sub-type of E.

public class Exception2 {
    public static void main(String[] args){
        try{
            System.out.println("Nothing to do here man...");
        } catch(Exception e){
            System.out.println("Seriously, This can"t happen man.");
        }
    }
}


If we see the above case, then we probably think that the Exception2 program also will not compile. But it will compile and will execute without any trouble. In catch clause Exception and Throwable are legal regardless of the contents of the corresponding try clause.