import java.io.*;
public class Question05 {
public static void main(
String[] args) {
Question05Sub myref = new Question05Sub();
try{
myref.test();
}catch(IOException ioe){}
}void
test() throws IOException{
System.out.println("In Question05");
throw new IOException();
}}
class Question05Sub extends Question05 {
void test() {
System.out.println("In Question05Sub");
}}
--------------------------------------------------------------------------------
Doubts:
1.Why does this give an error --- "Unreacheable catch block for IOException. This Exception is never thrown from the try statement."
2.Why does it compile if I change the IOException in catch to ArithmeticException or just plain Exception or any other exception.
3.Is there some special functionality or feature of IOException that I am not aware of.
Hi,
Let me try explaining it, I think my assumptions are correct.
Doubt 1 : When I compiled your code I got a compile time error :
exception java.io.IOException is never thrown in body of corresponding try statement
}catch(IOException ioe){}
Reason is : we are creating an object of a subclass which has test() method that does not throw any exception, so it is obvious from the error message that compiler does not expect an extra work done by the code to handle the erro which is surely never thrown.
If you change the method declaration of test() in sybclass as
void test() throws IOException{.... }
Program compiles perfectly fine. It is because you are creating an object of child class and hence child class method test() will be called.
If you create an object like this
Question05Sub myref = new Question05();
It compiles fine and runs due to DMD.
Doubt 2 & 3: It compiles when you change IOException to ArithmeticException, as ArithmeticException is Runtime Unchecked Exception category. Unchecked exceptions are not checked at compile time. BUT IOException is a checked Exception and hence is checked at compile time.
All checked exceptions either should be thrown or caught. Another example of checked exception is InterruptedExcption.
I hope it clear your doubt.