concept

Java treats exceptions as objects and defines a base class java.lang.throwable as a superclass for all exceptions. A number of Exception classes have been defined in the Java API, which fall into two categories: Error and Exception. Exception is divided into RuntimeException and non-runtimeException. Also known as Unchecked exceptions and Checked exceptions, these types of exceptions are generally exceptions that programs can handle themselves, and should be handled as often as possible in a program. Errors are errors that the program cannot handle, such as OutofMemoryErrors, ThreadDeath, etc. When these exceptions occur, the Java Virtual Machine (JVM) generally chooses to kill the thread. \

Runtime and non-runtime exceptions

Runtime exceptions are RuntimeException class and its subclasses abnormalities, such as NullPointerException, IndexOutOfBoundsException, exceptions are not checked exception, in the program can choose to capture processing, also can not deal with. These exceptions are usually caused by program logic errors, and programs should logically avoid them as much as possible. Non-runtime exceptions are exceptions other than RuntimeException and are of type to the Exception class and its subclasses. An exception that must be handled syntactically. If not handled, the program will fail to compile. For example, IOException, SQLException and user-defined Exception exceptions are not defined.

Exception catching and handling

The basic grammar

try {
    // Program code
} catch(Exception type Exception variable name) {// Exception handling code
} finally {
    // Must be executed before the method returns
}
Copy the code

Execution order

The catch block catches exceptions that occur in the try program code and handles them. There can be more than one catch statement block, but only one exception can be matched. Once an exception matching the Throwable type parameter is matched, the subsequent catch statement block will not be executed. Finally statement block will be executed before the method returns regardless of whether an exception occurs.

Matters needing attention

2. Multiple catch statements can have only one finally statement. 3. Multiple catch statements can match only one exception class and execute