0

In Java, checked exceptions are all instances of Throwable, except the instances of Error and RuntimeException. More specifically, if a class extends Exception, but not RuntimeException, it will be considered a checked exception.

This is why, for catch blocks catching a checked exception, the compiler checks if it can be actually thrown from the try block and reports a compiler error if this isn't the case:

import java.io.IOException;

public class ExceptionTest5 {

    public static void main(String[] args) {
        try{

        } catch (IOException e) {

        }
    }
}


ExceptionTest5.java:10: error: exception IOException is never thrown in body of corresponding try statement

which wouldn't be reported if RuntimeException was in the catch block.

However, nothing is being reported if Exception or Throwable are in the catch block, which makes them act like they were unchecked exceptions - which is directly opposed to the first sentence of this post, which I found in many different sources.

So, is Exception a checked or unchecked exception?

Naman
  • 27,789
  • 26
  • 218
  • 353
0lt
  • 283
  • 2
  • 13
  • 1
    Instances of `Exception` are neither checked nor unchecked. The checking of exceptions happens at compile time, when there are no instances. – Andy Turner Apr 14 '19 at 12:45
  • You are drawing the wrong conclusions. The error you see here is not directly because of checked-ness (or unchecked-ness), but rather because the compiler can guarantee (*) that exception won't be thrown in that block, so it would be redundant to catch it. – Andy Turner Apr 14 '19 at 12:49
  • (*) it can't actually, because you can trick the compiler to turn checked exceptions into unchecked exceptions, using generics. – Andy Turner Apr 14 '19 at 12:50

0 Answers0