Exception handling is an integral part of our daily development. Using exception handling allows our code to be more clearly regulated, allowing us to quickly locate exceptions and fix them to make our programs more robust. In addition to the user can also give a good error prompt. Below, we will combine an example to talk about exception handling mechanisms.
1. Example
1 Public classTestException {2 Publictestexception () {3 } 4 5 BooleanTestEx ()throwsException {6 BooleanRET =true; 7 Try { 8RET =testEx1 (); 9}Catch(Exception e) {TenSystem.out.println ("testEx, catch Exception"); OneRET =false; A Throwe; -}finally { -System.out.println ("testEx, finally; return value= "+ret); the returnret; - } - } - + BooleanTESTEX1 ()throwsException { - BooleanRET =true; + Try { ARET =testEx2 (); at if(!ret) { - return false; - } -System.out.println ("testEx1, at the end of Try"); - returnret; -}Catch(Exception e) { inSystem.out.println ("testEx1, catch Exception"); -RET =false; to Throwe; +}finally { -System.out.println ("testEx1, finally; return value= "+ret); the returnret; * } $ } Panax Notoginseng - BooleanTESTEX2 ()throwsException { the BooleanRET =true; + Try { A intb = 12; the intC; + for(inti = 2; I >=-2; i--) { -c = b/i; $System.out.println ("i=" +i); $ } - return true; -}Catch(Exception e) { theSystem.out.println ("testEx2, catch Exception"); -RET =false; Wuyi Throwe; the}finally { -System.out.println ("testEx2, finally; return value= "+ret); Wu returnret; - } About } $ - Public Static voidMain (string[] args) { -TestException TestException1 =Newtestexception (); - Try { A Testexception1.testex (); +}Catch(Exception e) { the E.printstacktrace (); - } $ } the}View Code
In the above code, there is an exception nested processing, seemingly cumbersome, but as long as we have mastered the exception handling process, it will be very simple.
First, the TestEx1 () method is called in the try block of TestEx (), and the TestEx2 () method is called in the try block of testEx1 ().
Second, in TesttestEx2 (), the For loop outputs 2, 1. When I=0, throws an exception, enters the catch block, executes the System.out.println ("testEx2, catch Exception"); ret = false; Enter finally block execution System.out.println ("testEx2, finally; return value= "+ ret); return ret; The value of RET is false.
then, jump back to TestEx1 (), enter the IF statement to satisfy the condition, and execute the statement in the finally block before return false . System.out.println ("testEx1, finally; return value= "+ ret); return ret; RET value is False
Finally, jumping back to Testex (), the Try statement execution completes into the finally block, execution System.out.println ("testEx, finally; return value= "+ ret); return ret;
2. Process of exception handling
1) When the try does not catch an exception: the statement in the TRY statement block is executed by itself, the program skips the Catch statement block, executes the finally statement block and the subsequent statement;
2) When a try catches an exception, there is no case in the catch statement block that handles this exception: When an exception occurs in a statement in a try statement block, and there is no catch statement block that handles the exception, the exception is thrown to the JVM for processing, and the statement in the finally statement block is executed. But the statement after the finally statement block will not be executed;
3) When a try catches an exception, there is a case in the catch statement block that handles this exception: in the TRY statement block is executed in order, when the execution to a statement exception, the program jumps to the catch statement block, and the catch statement block one by one, to find the corresponding handler, The other catch statement blocks will not be executed, and the statement after the exception is not executed in the TRY statement block, after the catch statement block executes, the statement in the finally statement block is executed, and finally the statement after the final statement block is executed;
When it comes to the finally statement, we should note:
1. The statements in the finally block will be executed regardless of whether the exception is caught or handled.
2, once a value is returned in try{}, if finally has a return value, the return value in finally overrides the return value of the try, if finally no return value, is the return value in the try.
3. If there is a return statement or a throw statement in a try or catch block, the statement in finally is executed before the throw or return statement, but updating the value in finally does not affect the return result of the try catch block. For details, refer to 52253768
3. Exceptions in Java
Java Exception class hierarchy diagram:
In Java, all exceptions have a common ancestor throwable (can be thrown). Throwable specifies the commonality of any problem that can be transmitted through a Java application using the exception propagation mechanism in the code. Throwable has two important subclasses: Exception (Exception) and error (Errors), both of which are important subclasses of Java exception handling, each of which contains a large number of subclasses.
Exception and Error
Error (Error): A bug that the program cannot handle, indicating a more serious problem in running the application. Most errors are unrelated to what the code writer does, and represent a problem with the JVM (the Java virtual machine) that is running the code. For example, the Java Virtual machine runs the error (virtual Machineerror) and OutOfMemoryError occurs when the JVM no longer has the memory resources required to continue the operation. When these exceptions occur, the Java Virtual machine (JVM) typically chooses to terminate the thread. These errors indicate that the failure occurred on the virtual machine itself, or when the virtual machine attempted to execute the application, such as a Java Virtual machine run error (virtual Machineerror), a class definition error (NOCLASSDEFFOUNDERROR), and so on. These errors are not available because they are outside the control and processing power of the application and are mostly not allowed when the program is running. For a well-designed application, even if it does, it should not be an attempt to deal with the anomalies that it causes. In Java, errors are described by the subclasses of the error.
Exception (Exception): is an exception that the program itself can handle.
The Exception class has an important subclass runtimeexception. The RuntimeException class and its subclasses represent errors thrown by the JVM common operation. For example, if you attempt to use null object references, divide by zero, or array out of bounds, the run-time exceptions (NullPointerException, ArithmeticException), and arrayindexoutofboundexception are raised respectively.
Note :
Differences between exceptions and errors: Exceptions can be handled by the program itself, and errors cannot be handled.
can check abnormal and non-check exception
In general, Java exceptions (including exception and error) are categorized as checked exceptions and non-checked exceptions (unchecked exceptions).
can check exceptions (compiler requirements must be disposed of exceptions): the correct program in operation, it is easy to appear, reasonable tolerance of abnormal conditions. Although the abnormal condition can be checked, it can be predicted to some extent, and in the event of such abnormal situation, it must be handled in some way.
Exception not checked ( compiler does not require forced disposition of exceptions ): Includes run-time exceptions (RuntimeException with its subclasses) and errors (error).
in addition to RuntimeException and its subclasses, other exception classes and their subclasses belong to the exception-checking. This exception is characterized by the Java compiler checking it, that is, when such an exception can occur in a program, either by capturing it with a try-catch statement or by declaring it with a throws clause, or the compilation will not pass.
Run-time exceptions and non-run-time exceptions
(Compile exception). These exceptions should be handled as much as possible in the program.
Run-time Exceptions: both the RuntimeException class and its subclass exceptions, such as NullPointerException (subscript out-of-bounds exception), are not checked for exceptions, the program can choose to capture the processing, or it can not be processed. These exceptions are usually caused by a program logic error, and the program should avoid this kind of exception as much as possible from a logical point of view. A run-time exception is characterized by the Java compiler not checking it, that is, when such an exception can occur in a program, even if it is not captured with the Try-catch statement, it is not thrown with the throws clause declaration, and it is compiled.
Non-runtime exception (compile exception): is an exception other than RuntimeException, and the type belongs to the exception class and its subclasses. From the point of view of the program syntax is the exception that must be handled, and if not handled, the program cannot be compiled through. such as IOException, SqlException, and user-defined exception exceptions, generally do not customize check exceptions.
Java exception Handling (i)