Java exception

Exceptions refer to unexpected conditions, such as file failure, network connection failure, and invalid parameters. An exception is an event that occurs during program execution and interferes with the normal flow of instructions. Java describes various exceptions through a number of subclasses of the Throwable class in the API. Thus, Java exceptions are objects, instances of Throwable subclasses that describe error conditions that occur in a piece of code. When a condition is generated, an error will throw an exception. Java exception class hierarchy diagram:





.png

In Java, all exceptions have a common ancestor (Throwable). Throwable specifies the commonality of any problems in code that can be transmitted through Java applications using exception propagation mechanisms. Throwable: There are two important subclasses: Exception and Error, both of which are important Java Exception handling subclasses, each containing a large number of subclasses. Error: An Error that the program cannot handle, indicating a serious problem in running the application. Most errors have nothing to do with what the code writer is doing, and instead represent problems with the JVM (Java Virtual Machine) while the code is running. For example, a Java Virtual Machine run error, an OutOfMemoryError occurs when the JVM no longer has the memory resources it needs to continue with the operation. When these exceptions occur, the Java Virtual Machine (JVM) typically selects thread termination. These errors indicate that the fault occurs on the VM itself or when the VM tries to execute an application, such as a Java Virtual Machine running error or a NoClassDefFoundError. These errors are not detectable because they are outside the control and processing capabilities of the application, and most of them are not allowed to occur while the program is running. Even if an error does occur, a properly designed application should not, by nature, attempt to handle the exception it raises. In Java, errors are described by subclasses of Error. Exception: An Exception that can be handled by the program itself. The Exception class has an important subclass, RuntimeException. The RuntimeException class and its subclasses represent errors thrown by “common JVM operations.” If, for example, try to use null object reference, dividing by zero or an array, respectively caused a runtime exception (NullPointerException, ArithmeticException) and ArrayIndexOutOfBoundException. Note: The difference between exceptions and errors: exceptions can be handled by the program itself, and errors cannot be handled. Generally, Java exceptions (including Exception and Error) are classified as both checked exceptions (Unchecked exceptions) and unchecked exceptions (unchecked exceptions). Traceable exceptions (exceptions required by the compiler to be handled) : Exceptions that are easy to occur during the running of the correct program. Although a traceable exception is an exception, it can be expected to some extent, and once it occurs, it must be handled in some way.

Except for RuntimeException and its subclasses, all Exception classes and their subclasses are traceable exceptions. This type of exception is checked by the Java compiler. That is, when such an exception is possible in a program, it is either caught with a try-catch statement or thrown with a throws clause declaration, or the compilation fails.

Uncheckable exceptions (exceptions that the compiler does not mandate): Includes runtime exceptions (runtimeExceptions and their subclasses) and errors.

Exception there are two broad categories of runtime and non-runtime exceptions (compile exceptions). Your program should handle these exceptions as much as possible.

Runtime exception: Are RuntimeException class and its subclasses abnormalities, such as NullPointerException (null pointer exception), IndexOutOfBoundsException anomaly) (subscript bounds, etc., these exceptions are not checked exception, in the program can choose to capture processing, also can not handle. These exceptions are usually caused by program logic errors, and programs should logically avoid them as much as possible.

The characteristic of a runtime exception is that the Java compiler does not check for it. That is, when such an exception may occur in a program, it will be compiled even if it is not caught with a try-catch statement or thrown with a throws clause declaration. Non-runtime exceptions (compiled exceptions) : Exceptions other than RuntimeException 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.

4. Exception handling mechanism

In Java applications, the exception handling mechanism is: throw an exception, catch an exception.

Throw exception: When a method fails to throw an exception, the method creates an exception object and delivers it to the runtime system. The exception object contains exception information such as the type of exception and the state of the program when the exception occurs. The runtime system is responsible for finding and executing the code that handles the exception.

Catch exception: After the method throws an exception, the runtime system turns to finding the appropriate exception handler. A potential exception handler is a collection of methods that remain in turn in the call stack when an exception occurs. An exception handler is a proper exception handler when the type of exception it can handle matches the type of exception thrown by the method. The run-time system starts with the method where the exception occurred and goes back to the methods in the call stack until it finds a method with an appropriate exception handler and executes it. When the runtime system traverses the call stack without finding a suitable exception handler, the runtime system terminates. Also, it means the termination of the Java program.

Java technology requires different exception handling for runtime exceptions, errors, or traceable exceptions.

Due to the untraceability of runtime exceptions, to make it more reasonable and easy to implement applications, Java specifies that runtime exceptions are automatically thrown by the Java runtime system, allowing applications to ignore runtime exceptions.

Java allows a method to not make any throw declarations for errors that may occur during a method run when the running method does not want to catch them. For the most part, Error exceptions are conditions that should never be allowed to occur and exceptions that a reasonable application should not catch.

For all traceable exceptions, Java dictates that a method must catch, or declare that it throws, out of the method. That is, when a method chooses not to catch a traceable exception, it must declare that it will throw an exception.

Methods that can catch exceptions need to provide exception handlers of the appropriate type. The exception caught can be an exception thrown by its own statement, thrown by a method called, or by a Java runtime system, for example. That is, any exception that a method can catch must be an exception thrown by Java code somewhere. Simply put, exceptions are always thrown first and then caught.

Any Java code can throw an exception, such as code you wrote yourself, code from a Java development environment package, or a Java runtime system. Anyone can throw an exception through a Java throw statement.

Any exception thrown from a method must use the throws clause.

Exceptions are caught by try-catch or try-catch-finally statements.

In general, Java states that you must catch or declare a throw for a traceable exception. Allows untraceable RuntimeExceptions and errors to be ignored.

4.1 Catching exceptions: try, catch, and finally

1. The try-catch statement

In Java, exceptions are caught by try-catch statements. Its general grammatical form is:

Type1} catch (Type2 ID2){// Catch (Type2 id2){// Catch (Type2 id2)}Copy the code

A pair of curly braces after the keyword try encloses a block of code where exceptions can occur, called a monitoring area. An exception object is created when a Java method encounters an exception during execution. The exception is thrown out of the monitor area, and the Java runtime system tries to find a matching catch clause to catch the exception. If there is a matching catch clause, the exception handling code is run, and the try-catch statement ends.

The rule of matching is that if the exception object thrown belongs to the exception class of the catch clause, or is a subclass of that exception class, the generated exception object is considered to match the type of exception caught by the catch block.

Example 1 catches the divisor zero exception thrown by the throw statement.

public class TestException { public static void main(String[] args) { int a = 6; int b = 0; Try {// try the monitoring areaif(b == 0) throw new ArithmeticException(); // Throw an exception system.out.println ("The value of a/b is:+ a / b); } catch (ArithmeticException e) {// Catch catching the exception system.out.println (arithmeticmeticException e)"Program exception, variable B cannot be 0.");  
        }  
        System.out.println("Program terminated as normal."); }}Copy the code

Running result: abnormal program, variable B can not be 0.

The program ends normally.

Example 1: Using the if statement in the try monitor area, raise the ArithmeticException exception when the error condition of “divisor 0” is true, create the ArithmeticException object, and throw the exception to the Java runtime. The system looks for the matched exception processor catch and runs the corresponding anomaly processing code to print out “the program is abnormal and variable B cannot be 0”. The try-catch statement ends and the program continues.

In fact, the divisor is zero and other ArithmeticException are subclasses of RuntimException. Runtime exceptions are automatically thrown by the runtime system without the need for a throw statement.

Example 2: Catch the ArithmeticException that the runtime system automatically throws with a divisor of 0.

public static void main(String[] args) {  
        int a = 6;  
        int b = 0;  
        try {  
            System.out.println("The value of a/b is: + a / b);  
        } catch (ArithmeticException e) {  
            System.out.println("Program exception, variable B cannot be 0.");  
        }  
        System.out.println("Program terminated as normal."); }}Copy the code

Running result: abnormal program, variable B can not be 0. The program ends normally.

The statement in Example 2:

System.out.println(“a/b的值是:” + a/b);

The ArithmeticException exception is raised with the “divisor is 0” error on the run. The runtime system creates an exception object and throws a monitoring area, which in turn matches the appropriate exception handler catch and executes the appropriate exception handling code.

Because the cost of checking for run-time exceptions far outweighs the benefit of catching them, run-time exceptions are not detectable. The Java compiler allows runtime exceptions to be ignored, and a method can neither catch nor declare a runtime exception to be thrown.

Example 3 does not catch or declare a runtime exception thrown.

public class TestException { public static void main(String[] args) { int a, b; a = 6; b = 0; // The divisor b is 0 system.out.println (a/b); }}Copy the code

Results: the Exception in the thread “is the main” Java. Lang. ArithmeticException: / by zero at Test.TestException.main(TestException.java:8)

Example 4: The program may have a zero divisor exception and an out-of-bounds array subscript exception.

public class TestException {  
    public static void main(String[] args) {  
        int[] intArray = new int[3];  
        try {  
            for (int i = 0; i <= intArray.length; i++) {  
                intArray[i] = i;  
                System.out.println("intArray[" + i + "] =" + intArray[i]);  
                System.out.println("intArray[" + i + "] die" + (i - 2) + "Value:"  
                        + intArray[i] % (i - 2));  
            }  
        } catch (ArrayIndexOutOfBoundsException e) {  
            System.out.println("IntArray array index out of bounds exception.");  
        } catch (ArithmeticException e) {  
            System.out.println("0 divisor exception.");  
        }  
        System.out.println("Program terminated as normal."); }}Copy the code

Running results:

intArray[0] = 0

IntArray [0] mode-2 value: 0

intArray[1] = 1

IntArray [1] mode-1 value: 0

intArray[2] = 2

The divisor is 0.

The program ends normally.

Example 4: The divisor may be 0, and the array subscript may be out of bounds. The ArithmeticException exception type is matched first while the program is running, so the matching catch statement is executed:

catch (ArithmeticException e){  
      System.out.println("0 divisor exception.");  
 } 
Copy the code

It is important to note that once a catch catches a matching exception type, it enters the exception-handling code. Once the processing ends, the entire try-catch statement ends. Other catch clauses no longer have the opportunity to match and catch the exception type.

Java describes exception types through exception classes, the hierarchy of which is shown in Figure 1. For exception programs with more than one catch clause, try to put the catch clause that catches the low-level exception class first, and try to put the catch clause that catches the relatively high-level exception class later. Otherwise, the catch clause that catches the underlying exception class may be masked.

RuntimeException exception class various common abnormalities, including runtime ArithmeticException classes and ArrayIndexOutOfBoundsException class is a subclass of it. Therefore, the catch clause of the RuntimeException class should come last, otherwise it may mask subsequent specific exception handling or cause a compilation error.