The architecture of exceptions

Java.lang.Throwable ① Error ① Exception ② Exception ① java.lang.Throwable Compile-time exception: Exception that occurs during compilation (when the javac.exe command is executed) ⅱ. Runtime exception: An exception that occurs during runtime (when executing the java.exe command)Copy the code

When executing a program, if an exception occurs, the code after the exception stops executing!

How to handle Exception

Java provides a catch model for exceptions

1. "catch ": Grabs the object of the exception class thrown in the previous step. How to grasp? (1) try-catch-finally 2 throws + Exception type 2. "throw ": When we execute code, whenever an exception occurs, we generate an object of the corresponding type in the exception code and throw it (automatically/manually (throw + new exception class)). Once an object of the exception class is thrown, The program then terminates the execution of the exception class object and throws it to the method caller. Java provides two ways to handle an exception class objectCopy the code

Exception classes, either ready-made or self-created

Iii. Handling methods of exceptions:

}catch(Exption2 e2){// Catch (Exption2 e2){// Finally {/ = LLDB (LLDB) LLDB (LLDB) LLDB (LLDB) LLDB (LLDB) LLDB (LLDB) LLDB (LLDB) E.printstacktrace () ③ Multiple catch statements can be used to match the type of the exception class in a try from the top down. (4) If the exception is handled, the code continues to execute. (5) If the type of exception in the catch is "parallel", then the sequence is ok. If multiple exception types in a catch are "contained", the subclass must be handled before the parent class. (6) In the finally file, the code must be executed. (7) In the finally file, the code must be executed. (8) In the finally file, the code must be executed regardless of whether there is an exception in the try or catch. The type of the exception object to be explicitly thrown in the declaration of the method. Public static void method() throws Exception{} ③ When an Exception occurs inside the method, an Exception class object is thrown to the method caller. ④ The Exception object can be thrown up layer by layer until main. Of course, it can be handled by try-catch-finally during an upward throwCopy the code

Runtime exceptions can be handled without being explicit

Compile-time exceptions must be handled explicitly

How to customize an exception class

① Custom exception classes inherit from existing exception classes ② provide a sequence number that provides several overloaded constructorsCopy the code
public class MyException extends Exception{ static final long serialVersionUID = -70348975766939L; public MyException(){} public MyException(String msg){ super(msg); }}Copy the code

A method overridden by a subclass that throws an exception of a type that can only be a subclass or itself of the overridden method’s exception class

Throw and throws