Article From:

        Exception handling is an integral part of our daily development. Exception handling can make our code clearer and more standardized, allowing us to quickly locate exceptions and make our programs more robust. In addition, it can give users a good error prompts. Next, we will combine an exampleZi Lai talked about the mechanism of exception handling.


 1 public class TestException {  
 2     public TestException() {  
 3     }  
 5     boolean testEx() throws Exception {  
 6         boolean ret = true;  
 7         try {  
 8             ret = testEx1();  
 9         } catch (Exception e) {  
10             System.out.println("testEx, catch exception");  
11             ret = false;  
12             throw e;  
13         } finally {  
14             System.out.println("testEx, finally; return value=" + ret);  
15             return ret;  
16         }  
17     }  
19     boolean testEx1() throws Exception {  
20         boolean ret = true;  
21         try {  
22             ret = testEx2();  
23             if (!ret) {  
24                 return false;  
25             }  
26             System.out.println("testEx1, at the end of try");  
27             return ret;  
28         } catch (Exception e) {  
29             System.out.println("testEx1, catch exception");  
30             ret = false;  
31             throw e;  
32         } finally {  
33             System.out.println("testEx1, finally; return value=" + ret);  
34             return ret;  
35         }  
36     }  
38     boolean testEx2() throws Exception {  
39         boolean ret = true;  
40         try {  
41             int b = 12;  
42             int c;  
43             for (int i = 2; i >= -2; i--) {  
44                 c = b / i;  
45                 System.out.println("i=" + i);  
46             }  
47             return true;  
48         } catch (Exception e) {  
49             System.out.println("testEx2, catch exception");  
50             ret = false;  
51             throw e;  
52         } finally {  
53             System.out.println("testEx2, finally; return value=" + ret);  
54             return ret;  
55         }  
56     }  
58     public static void main(String[] args) {  
59         TestException testException1 = new TestException();  
60         try {  
61             testException1.testEx();  
62         } catch (Exception e) {  
63             e.printStackTrace();  
64         }  
65     }  
66 }  

View Code

In the above code, abnormal nesting processing appears to be very troublesome, but as long as we master the process of exception handling, it will be very simple.

First, the testEx1 () method is called in the try block of testEx (), and the testEx2 () method is invoked in the try block of testEx1 ().

Secondly, in testtestEx2 (), the for loop outputs 2, 1. When i=0, throws an exception, enters the catch block, and executes System.out.println.“testEx2, catch exception”);  ret = false; Go into the finally block executionSystem.out.println(“testEx2, finally; return value=” + ret);   return ret;  retThe value is false.

Then, jump back to testEx1 (), enter the if statement to satisfy the condition, execute the statement in the finally block before return false.System.out.println(“testEx1, finally; return value=” + ret);  return ret;   retThe value is false

Finally, jump back to testEx (), and the try statement completes the finally block execution.System.out.println(“testEx, finally; return value=” + ret);  return ret;  

2、Process of exception handling

1)When try does not catch exceptions, statements in the try statement block are executed one by one. The program will skip the catch statement block and execute the finally statement block and subsequent statements.

2)When the try captures the exception, the exception is not handled in the catch statement block: when an exception in the try statement block appears, and there is no catch block to deal with the exception, the exception will be thrown to the JVM processing, and the statements in the finally statement block will be held.OK, but the statement after the finally statement block will not be executed.

3)When the try captures the exception, there is a case in the catch statement block to handle this exception: in the try block, it is executed in order, when an exception is executed to a certain statement, the program will jump to the block of the catch statement and match the catch block by one by one to find the corresponding place.In the program, other catch block blocks will not be executed, and the statements in the try statement block will not be executed after the exception. After the catch block is executed, the statements in the block of the finally statement are executed, and the statements after the finally block are executed.

When it comes to finally statements, we should pay attention to:

1、Whether or not the exception is captured or handled, the statements in the finally block will be executed.

2、Once a value is returned in the try{}, if finally has a return value, the return value in the finally will cover the return value of the try, and if finally has no return value, it is the return value in the try.

3、If there are return statements or throw statements in the try or catch blocks, the statements in the finally will be executed before the throw or return statements, but the update of the value in finally does not affect the return results of the try catch block.For details, please refer to

3、javaAbnormality in the middle

JavaException class hierarchy diagram:

 exception class


       In Java, all exceptions have a common ancestor Throwable (which can be thrown). Throwable specifies the commonality of any problem that the exception propagation mechanism can transmit through the Java application in the code. Throwable has two important thingsSubclasses: Exception (exception) and Error (error), the two are important subclasses of Java exception handling, each of which contains a large number of subclasses.

ExceptionAnd Error

       Error(Error: error that the program can not handle, which represents a more serious problem in running the application. Most errors have nothing to do with the operations performed by the code writer, and indicate the problems of JVM (Java virtual machine) when the code runs. For example, the Java virtual machine runs an error (VirtualMachineError), when JVM no longer has the memory resources needed to continue executing the operation, OutOfMemoryError will appear. When these anomalies occur, the Java virtual machine (JVM) generally chooses thread termination. These errors indicate that the failure occurredThe virtual machine itself, or occurs when the virtual machine tries to execute the application, such as the Java virtual machine running error (Virtual MachineError), the class definition error (NoClassDefFoundError), and so on. These errors are unchecked because of themIn addition to the control and processing capabilities of the application, most of them are not allowed when the program is running. For a reasonably designed application, even if there is a mistake, it should not attempt to deal with the abnormal situation caused by it. In Java, the error passes through the ErroThe subclass description of the R.

       Exception(Exception): an exception that the program itself can handle.

       Exception The class has an important subclass, RuntimeException. The RuntimeException class and its subclass represent errors caused by “JVM common operations”. For example, if you attempt to use a null value object reference, a divisor is zero or an array bounds, the runtime is raised separately.Exceptions (NullPointerException, ArithmeticException) and ArrayIndexOutOfBoundException.

       Be careful

       The difference between exception and error is that exceptions can be handled by the program itself, and errors can not be processed.

Abnormity and unchecked exception

       In general, Java exceptions (including Exception and Error) are divided into exceptions (checked exceptions) and undetected exceptions (unchecked exceptions).
       Exceptions can be checked (exceptions that the compiler requires to be handled): the right procedure is easy to appear in operation, and the reasonable exception is allowed. Although the exception is abnormal, it can be expected to a certain extent, and once this abnormal situation occurs, it must be carried out in some way.Handle.

       Unchecked exceptions (The exception that the compiler does not require mandatory disposal):It includes runtime exceptions (RuntimeException and its subclasses) and errors (Error).

       In addition to RuntimeException and its subclasses, other Exception classes and their subclasses are exceptions.The feature of this exception is that the Java compiler will check it, that is, when this kind of exception may appear in the program, either it is captured with a try-catch statement or the throws clause is declared to be thrown out, otherwise the compilation will not pass.

Runtime exception and non runtime exception   

       (Compile an exception). These exceptions should be handled as much as possible in the program.

       Runtime exception: RuntimeException class and its subclass exceptions, such as NullPointerException (subscript transboundary exception), etc., these exceptions do not check the exception, the program can select the capture processing, and can not handle it. These exceptions are generallyDue to procedural logic errors, programs should avoid such anomalies from logical perspective as far as possible.The characteristic of the runtime exception is that the Java compiler does not check it, that is to say, this kind of exception may occur in the program, even if no try-catch statement is used to capture it, nor is it thrown out with the throws clause declaration, and it will also be compiled and passed.

       Non runtime exception (compilation exception): exceptions other than RuntimeException, which belong to the Exception class and its subclasses. From the point of view of program syntax, it is an exception to be processed. If it is not processed, the program can not be compiled. Such as IOExCeption, SQLException, and user defined Exception exceptions do not customize checking exceptions in general.

Link of this Article: Java exception handling (1)

Leave a Reply

Your email address will not be published. Required fields are marked *