This is the sixth day of my participation in the August More text Challenge. For details, see: August More Text Challenge

1, Java exception class hierarchy diagram

2, Error, Exception

In Java, all exceptions have a common ancestor, the Java.lang.Throwable class.

The Throwable class has two important subclasses: Exception and Error, each of which has a large number of subclasses.

Exceptions can be handled by the program itself (try-catch), errors cannot be handled (only to be avoided);

  • ErrorErrorIt’s an error that the program can’t handle. We can’t pass itcatchTo capture. Examples include Java Virtual machine running error (Virtual MachineErro), insufficient vm memory error (OutOfMemoryError), class definition error (NoClassDefFoundError), and so on. When these exceptions occur, the Java Virtual Machine typically selects thread termination.
  • Exception: Exceptions that can be handled by the program itself can be passedcatchTo capture.ExceptionCan be divided intoInspected anomaly(must deal with) andNot checked for abnormalities(It may not be handled).
    • Inspected anomaly
      • Java code is compiled if the checked exception is notcatch/throwIf it’s processed, it won’t compile;
      • In addition toRuntimeExceptionAnd its subclasses, otherExceptionClass and its subclasses are checked exceptions;
      • Common abnormalities are as follows:IOException,ClassNotFoundException,SQLException
    • Not checked for abnormalities
      • Java code can compile without handling unchecked exceptions.
      • RunntimeExceptionAnd its subclasses are collectively referred to as unchecked exceptions;
      • Such as:NullPointerException(null pointer exception),NumberFormatException(String converted to number),ArrayIndexOutOfBoundsException(array index out of bounds),ClassCastException(Type conversion exception),ArithmeticException(arithmetic error), etc

3, try-catch – finally

  • Try block: used to catch an exception. It can be followed by zero or more catch blocks. If there is no catch block, a finally block must follow.

  • Catch block: for handling exceptions caught by a try;

  • Finally block: Statements ina finally block are executed regardless of whether an exception is caught or handled. When a return statement is encountered ina try or catch block, the finally block is executed before the method returns

    public static int test(a){
        try{
            return 5;
        } catch (Exception e){
            e.printStackTrace();
        } finally{
            return 8; }}// The final return is: 8
    Copy the code

** Finally will not be executed in the following three special cases:

  1. intrycatchUsing a piece ofSystem.exit(0)Exit the program;
  2. The thread in which the program is running dies.
  3. Close the CPU.