4

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

            }
        }
    }
Saveendra Ekanayake
  • 3,153
  • 6
  • 34
  • 44
  • If this the exact code you've,, it should compile. – Rohit Jain Sep 08 '15 at 17:19
  • @RohitJain No It will provide following error because of catch(IOException e). Error Message - Exception in thread "main" java.lang.Error: Unresolved compilation problem: Unreachable catch block for IOException. This exception is never thrown from the try statement body at Demo.main(Demo.java:6) – Saveendra Ekanayake Sep 08 '15 at 17:21
  • Possible duplicate of http://stackoverflow.com/questions/23817401/catch-exceptions-which-are-not-thrown-locally – yshavit Sep 08 '15 at 17:27

3 Answers3

9

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.

rgettman
  • 176,041
  • 30
  • 275
  • 357
0

To answer why Exception block is compiling and IOException is not... Simply because everything inherited from Exception class, it includes all types exceptions such as IOException, RuntimeException, etc. When you specify catching Exception, nothing in the code necessarily have to throw it as a RuntimeException thrown at runtime and code compiler can't predict that one happening. But IOException is a specific exception that happens only in certain cases, thus compiler knows exactly when it might happen, and if it doesn't detect any code that might throw it, it will not compile.

Kat
  • 11
  • 1
0

See, the main reason is, you can catch any RuntimeException, doesn't matter it is thrown from the try block or not and RuntimeException is the class which extends Exception class itself. So, being a parent class, catch "Exception" is always allowed. In your case IOException checked exception, it is only allowed if you try block having a probability of throwing it.