An exception is said to be _thrown_ from the point where it occurred and is said to be _caught_ at the point to which control is transferred.

exception family tree

IMG_2690

All exceptions are inherited from Throwable.

All run-time exception classes and error classes are unchecked exception classes, and the rest are checked exception classes.

That is, the checked exception classes are all subclasses of Throwable other than RuntimeException and its subclasses and Error and its subclasses.

play with finally block

If you put a finally block after a try and its associated catch blocks, then once execution enters the try block, the code in that finally block will definitely be executed except in the following circumstances:

  1. An exception arising in the finally block itself.
  2. The death of the thread.
  3. The use of System.exit()
  4. Turning off the power to the CPU. finally block is always executed before the try-catch blocks exit, including:
  1. return
void foo() {
    try {
        return;
    } finally {
        System.out.println("finally executed"); // execute before return
    }
}
  1. no exception, execute sequentially
void foo() {
    try {
        // some code
    } finally {
        System.out.println("finally executed"); // execute before try block ends
    }
}
  1. has exception, but no catch
void foo() {
    try {
        throw new Exception("11");
        // some code
    } finally {
        System.out.println("finally executed"); // execute before throwing the exception
    }
}
  1. has exception, but caught successfully
void foo() {
    try {
        throw new Exception("11");
        // some code
    } catch(Exception e) {
        // some code
    } finally {
        System.out.println("finally executed"); // execute before the catch block ends
    }
}
  1. has exception, try to catch but failed
void foo() {
    try {
        throw new Exception("11");
        // some code
    } catch(RuntimeException e) {
        // some code
    } finally {
        System.out.println("finally executed"); // execute before throwing the exception
    }
}

For more details about finally behavior, please refer to finally execution in try-catch-finnally blocks

exception catch order

If class BaseException is the super class of class DerivedException, and you write the catch clause of BaseException ahead of DerivedException, then a compilation error will show.

try
{
    int x = 0;
    int y = 5 / x;
}
catch (Exception e)
{
    System.out.println("Exception");
}
catch (ArithmeticException ae) // compiler error: Exception "java.lang.ArithmeticException" has already been caught
{
    System.out.println(" Arithmetic Exception");
}
System.out.println("finished");