10
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) ?

2 Answers 2

21

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:

References:

Sign up to request clarification or add additional context in comments.

5 Comments

You don't need to handle RuntimeException, does not sound correct?
There are some RuntimeExceptions that should be handled, even though they don't have to be caught/declared. NumberFormatException is a common example.
@chrylis, should be handled and need to be handled are actually a big difference.
@JunedAhsan. I said that in terms of Compiler error not being thrown.
@RohitJain Yes i wondered, there should be some rationale ;-)
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.