Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IOException vs RuntimeException Java

class Y {
    public static void main(String[] args) throws RuntimeException{//Line 1
        try {
            doSomething();
        }
        catch (RuntimeException e) {
            System.out.println(e);
        }
    }
    static void doSomething() throws RuntimeException{ //Line 2
        if (Math.random() > 0.5) throw new RuntimeException(); //Line 3
        throw new IOException();//Line 4
    }
}

When I throw two types of exception (IOException in Line4 and RunTimeException in Line3), I found that my program does not compile until I indicate "IOException" in my throws clauses in Line 1 & Line 2.

Whereas if I reverse "throws" to indicate IOException being thrown, the program does compile successfully as shown below.

class Y {
    public static void main(String[] args) throws IOException {//Line1
        try {
            doSomething();
        }
        catch (RuntimeException e) {
            System.out.println(e);
        }
    }
    static void doSomething() throws IOException {//Line 2
        if (Math.random() > 0.5) throw new RuntimeException();//Line 3
        throw new IOException();//Line 4
    }
}

Why should I always use "throws" for IOException even though RuntimeException is also thrown (Line 3) ?

like image 205
UnderDog Avatar asked Aug 24 '13 08:08

UnderDog


2 Answers

Because IOException is a Checked Exception, which should be either handled or declared to be thrown. On contrary, RuntimeException is an Unchecked Exception. You don't need to handle or declare it to be thrown in method throws clause (Here I mean, it would be syntactically correct if you don't handle the unchecked exception. Compiler won't be angry). However there are some situation, where you need to handle and act accordingly for some Unchecked Exception.


Related Post:

  • Java: checked vs unchecked exception explanation
  • When to choose checked and unchecked exceptions

References:

  • JLS - Kinds and Cause of Exceptions
  • Oracle Exceptions Tutorial
like image 191
Rohit Jain Avatar answered Oct 07 '22 06:10

Rohit Jain


The reason is that there are two different types of exceptions in this case. One is a checked exception which ought to be handled by the programmer and the other one is an unchecked exception which doesn't require special handling.

like image 43
svz Avatar answered Oct 07 '22 05:10

svz