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) ?
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With