Site Search:

Differentiate among checked exceptions, unchecked exceptions, and Errors


Back OCAJP



For the sake of OCAJP test, we need to remember this exception extending relationship, and which one should and have to be catch.


A runtime exception or unchecked exception is the RuntimeException class and its subclasses. It is ok for a program to catch it, but it is not a requirement.

Checked exception is the subclass of Exception but not subclass of RuntimeException. The program have to catch it.

Error is subclass of Error, program should not catch it.





OCAJP>cat test.java 
import java.util.*;
class test {
  public static void main(String...args) {
    test t = new test();
    t.tester(args[0]);
  }
  public void tester(String a) {
    try{
       switch(a) {
         case "1":
           throw new RuntimeException();
         case "2":
           throw new Exception();
         case "3":
           throw new Error();
         case "4":
           throw new Throwable();
         default:
           //throw new Object();  //error: incompatible types: Object cannot be converted to Throwable
       }
    } catch(RuntimeException r) {
      System.out.println("optional");
    } catch(Exception ex) {
      System.out.println("mandantory, otherwise won't compile");
    } catch(Error e) {
      System.out.println("should not, but a valid syntax");
    } catch(Throwable t) {
      System.out.println("can catch Throwable, a valid syntax");
    }
    switch(a) {
      case "1":
        throw new RuntimeException("something bad will happen at run time, however, you can ignore it during compile");
      case "2":
        //throw new Exception("something you can not ignor");  //error: unreported exception Exception; must be caught or declared to be thrown
      case "3":
        throw new Error("fatal error beyond fix, don't catch it, should let the program fail");
      case "4":
        //throw new Throwable("It can be anything bad, not sure what it is");  //error: unreported exception Throwable; must be caught or declared to be thrown
      default:
    }
  }
}
OCAJP>javac test.java 
OCAJP>java test
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at test.main(test.java:5)
OCAJP>java test 1
optional
Exception in thread "main" java.lang.RuntimeException: something bad will happen at run time, however, you can ignore it during compile
at test.tester(test.java:32)
at test.main(test.java:5)
OCAJP>java test 2
mandantory, otherwise won't compile
Exception in thread "main" java.lang.Error: fatal error beyond fix, don't catch it, should let the program fail
at test.tester(test.java:36)
at test.main(test.java:5)
OCAJP>java test 3
should not, but a valid syntax
Exception in thread "main" java.lang.Error: fatal error beyond fix, don't catch it, should let the program fail
at test.tester(test.java:36)
at test.main(test.java:5)
OCAJP>java test 4
can catch Throwable, a valid syntax
OCAJP>java test 5
OCAJP>

Back OCAJP