An in-depth understanding of Java Exception Handling Mechanism

Source: Internet
Author: User
Tags finally block throwable

 

1 Guide
Try... Catch... Finally
I'm afraid it's a familiar statement, and it seems easy to understand logically. However, the lessons I personally learned tell me that this is not as simple and obedient as I imagined. Believe it? Let's take a look at the following code and "Guess" what the result will be after it is executed? Do not look back at the answer or execute the code to see the real answer. If your answer is correct, you don't have to waste time reading this article.

Package myexample. testexception;
Public class testexception {
Public testexception (){

}
Boolean testex () throws exception {

Boolean ret = true;

Try {

Ret = testex1 ();

} Catch (exception e ){

System. Out. println ("testex, catch exception ");

Ret = false;

Throw E;

} Finally {

System. Out. println ("testex, finally; return value =" + RET );

Return ret;

}

}
Boolean testex1 () throws exception {

Boolean ret = true;

Try {

Ret = testex2 ();

If (! RET ){

Return false;

}

System. Out. println ("testex1, at the end of try ");

Return ret;

} Catch (exception e ){

System. Out. println ("testex1, catch exception ");

Ret = false;

Throw E;

}

Finally {

System. Out. println ("testex1, finally; return value =" + RET );

Return ret;

}

}
Boolean testex2 () throws exception {

Boolean ret = true;

Try {

Int B = 12;

Int C;

For (INT I = 2; I >=- 2; I --){

C = B/I;

System. Out. println ("I =" + I );

}

Return true;

} Catch (exception e ){

System. Out. println ("testex2, catch exception ");

Ret = false;

Throw E;

}

Finally {

System. Out. println ("testex2, finally; return value =" + RET );

Return ret;

}

}

 

Public static void main (string [] ARGs ){

Testexception testexception1 = new testexception ();

Try {

Testexception1.testex ();

} Catch (exception e ){

E. printstacktrace ();

}

}

}

 

What is your answer? Is it the answer below?

I = 2

I = 1

Testex2, catch exception

Testex2, finally; return value = false

Testex1, catch exception

Testex1, finally; return value = false

Testex, catch exception

Testex, finally; return value = false

If your answer is as mentioned above, you are wrong. ^ _ ^, You are advised to take a closer look at this article or take the above Code and modify, execute, and test it according to various situations, you will find that many things are not as simple as you thought.

The correct answer is now published:

I = 2

I = 1

Testex2, catch exception

Testex2, finally; return value = false

Testex1, finally; return value = false

Testex, finally; return value = false

2 Basic Knowledge
2.1 concepts
An exception is an abnormal event that occurs during the program running, for example, in addition to 0 overflow, array out-of-bounds, and file not found. The occurrence of these events will prevent the program from running properly. In order to enhance the robustness of the program, it is necessary to take into account possible abnormal events and handle them accordingly during program design. In the C language, the IF statement is used to determine whether exceptions occur. At the same time, the called function perceives and processes the exception events generated in the called function through the return values of the called function. The full-process variable errono is often used to reflect the type of an exception event. However, this error handling mechanism may cause many problems.

Java uses an object-oriented method to handle exceptions.In the process of running a method, if an exception occurs, the method generates an object representing the exception and delivers it to the runtime system, the runtime system looks for the corresponding code to handle this exception. The process of generating an exception object and submitting it to the runtime system is called throwing an exception. During the runtime, the system searches for the method call stack and starts to refresh from the method that generates the exception until it finds the method that contains the corresponding exception processing. This process is called catch) one exception.
2.2throwable class and its subclass
When you use an object-oriented method to process exceptions, you must create a class hierarchy. The throwable class is located at the top of the hierarchy. Only its descendants can be discarded as an exception. Figure 1 shows the level of the exception handling class.

As you can see,Throwable has two direct subclasses: Error and exception.. Error objects (such as dynamic connection errors) are generated and discarded by Java virtual machines (normally, Java programs do not handle such exceptions). Exception objects are processed or discarded by Java programs. Different subclasses correspond to different types of exceptions. Runtimeexception indicates exceptions generated by the Java Virtual Machine at run time, such as arithmeticexception (caused by an exception of 0) and arrayindexoutofboundsexception, which are exceptions of non-runtime, for example, the input/output exception ioexception. The Java compiler requires the Java program to capture or declare all non-runtime exceptions, but the runtime exceptions can not be processed.
Figure 1 exception handling class hierarchy
2.3 Exception Handling keywords
Java exception handling is implemented through five keywords: Try, catch, throw, throws, and finally. The following keywords are explained in JB's online help:

Throws: lists the exceptions A method cocould throw.

Throw: transfers control of the method to the exception handler.

Try: Opening exception-handling statement.

Catch: captures the exception.

Finally: runs its code before terminating the program.

2.3.1try statement
The try statement specifies a piece of code with braces {}, which may discard one or more exceptions.

2.3.2catch statement 
The parameters of a catch statement are similar to the declaration of a method, including an exception type and an exception object. The exception type must be a subclass of the throwable class, which specifies the exception type processed by the catch statement. The exception object is generated and captured by the runtime system in the code block specified by try, the braces contain the processing of objects, and the methods of objects can be called.

There can be multiple catch statements to handle exceptions of different classes. During Java runtime, the system detects the exception types processed by each catch statement from top to bottom until a catch statement with the matching types is found. Here, type matching means that the exception type processed by catch is exactly the same as the type of the generated exception object or its parent class. Therefore, the sort order of catch statements should be from special to general.

You can also use a catch statement to process multiple exception types. In this case, its exception type parameter should be the parent class of these multiple exception types, in the program design, You must select the exception handling type of the catch statement according to the specific situation.

2.3.3 finally statement
In the Code defined by try, when an exception is discarded, the subsequent code will not be executed. You can use finally statements to specify a piece of code. No matter whether the exception type of the catch statement is the same as that of the discarded exception type in the block specified by try, the Code specified by finally must be executed, it provides a uniform exit. You can usually clear resources in finally statements. For example, close open files.

2.3.4 throws statement 
Throws always appear in a function header to indicate various exceptions that a member function may throw. For most exception subclasses, the Java compiler forces you to declare the types of exceptions thrown in a member function. If the exception type is error, runtimeexception, or their subclass, this rule does not work because it is not expected to appear in the normal part of the program. If you want to explicitly throw a runtimeexception, you must use the throws statement to declare its type.

2.3.5throw statement 
Throw always appears in the function body to throw an exception. The program will terminate immediately after the throw statement, the statement after it cannot be executed, and then in all try blocks containing it (possibly in upper-layer function calls) search for try blocks containing matched catch clauses from the inside out.
3. Keyword and statement process details
3.1try nesting

You can write a try statement outside a member function call. In this member function, write another try statement to protect other code. Whenever a try statement is encountered, the exception framework is placed on the stack until all try statements are completed. If the next try statement does not process an exception, the stack will be opened until a try statement is encountered. The following is an example of try statement nesting.

Class multinest {

Static void procedure (){

Try {

Int A = 0;

Int B = 42/;

} Catch (Java. Lang. arithmeticexception e ){

System. Out. println ("in procedure, catch arithmeticexception:" + E );

}

}
Public static void main (string ARGs []) {

Try {

Procedure ();

} Catch (Java. Lang. Exception e ){

System. Out. println ("in main, catch exception:" + E );

}

}

}
The execution result of this example is:

In procedure, catch arithmeticexception: Java. Lang. arithmeticexception:/by zero

The member function procedure has its own try/catch control, so main does not need to process arrayindexoutofboundsexception. Of course, if we do the test in the beginning, when an exception is caught in procedure, the throw e Statement is used to throw the exception. The main can still catch and handle the exception thrown by procedure. For example, after the throw e is added to the system. Out statement in the catch statement of the procedure function, the execution result is changed:

In procedure, catch arithmeticexception: Java. Lang. arithmeticexception:/by zero

In Main, catch exception: Java. Lang. arithmeticexception:/by zero
3.2 execution process and result of the try-Catch Block
Compared with the try-catch-Finally block, the execution process and result of try-catch are relatively simple.

The first statement in the try statement block may be executed in the following three cases:

1. If all the statements in the try block are executed normally, no other "dynamic" statements will be executed, and the entire try-catch block will be completed normally.

2. If the try statement block encounters an exception V during execution, it can be processed in two situations:

If exception V can be caught by the Catch Block corresponding to the try, the first catch block to the exception (also the Catch Block closest to the try that matches the V) the Catch Block is executed. If the Catch Block is executed normally, the result of the try-Catch Block is "normal completion". If the Catch Block is suddenly aborted due to the cause of R, the result of the try-Catch Block is "due to the reason that r suddenly stops (completes abruptly )".

If the exception V does not match the Catch Block, the result of this try-Catch Block is "Completes abruptly )".

3. If try suddenly suspends (completes abruptly) for other reasons, the result of this try-Catch Block is "completes abruptly )".

3.3 try-catch-finally: Execution process and result of the program block
The execution process and results of try-catch-finally blocks are complex.

The first statement in the try statement block may be executed in the following three cases:

1. If all the statements in the try block are executed normally, the residence of the Finally block will be executed. There are two possible cases:

If the Finally block is successfully executed, the entire try-catch-Finally block is successfully completed.

If the Finally block is suddenly terminated due to the reason R, the end of the try-catch-Finally block is "The Cause R is suddenly aborted (completes abruptly )"

2. If the try statement block encounters an exception V during execution, it can be processed in two situations:

If exception V can be caught by the Catch Block corresponding to the try, the first catch block to the exception (also the Catch Block closest to the try that matches the V) will be executed; there will be two execution results:

If the Catch Block is executed normally, the Finally block will be executed in two cases:

If the Finally block is successfully executed, the entire try-catch-Finally block is successfully completed.

If the Finally block is suddenly terminated due to the reason R, the end of the try-catch-Finally block is "The Cause R is suddenly aborted (completes abruptly )"

If the Catch Block is suddenly terminated due to the reason R, the finally module will be executed in two cases:

If the Finally block runs smoothly, the end of the entire try-catch-Finally block is "due to the reason R suddenly aborted (completes abruptly )".

If the Finally block is suddenly terminated due to the reason s, the end of the entire try-catch-Finally block is "Completes abruptly", and R will be discarded.

(Note: This is exactly the same as our example. Although we throw an exception using throw e in testex2, because testex2 has a Finally block, the finally block execution result is complete abruptly (Don't underestimate this most used return, it is also one of the reasons for complete abruptly-the cause of complete abruptly is described later), so the result of the entire try-catch-Finally block is "complete abruptly ", therefore, when testex2 is called in testex1, the exception thrown in testex1 cannot be caught, but the return result in finally can only be obtained.

If you want to return values by capturing exceptions of the called lower-level functions in your code, pay attention to the finally statements in the lower-level functions you call, it may make the exception you throw out not really visible to the upper-level call function. Of course, this situation can be avoided. Take testex2 as an example: If you must use finally and capture the E of throw in catch in testex1, you can remove the return in finally in testex2.

This has already happened in the MIB of omc2.0: Server exceptions cannot be completely reported to the client .)

If exception V does not match catch blocks, the finally module is executed in two cases:

If the Finally block runs smoothly, the finally end of the entire try-catch-Finally block is "Completes abruptly" because an exception V is thrown )".

If the Finally block is suddenly terminated due to the reason s, the end of the entire try-catch-Finally block is "Completes abruptly", and the exception V will be discarded.

If try suddenly terminates (completes abruptly) for other reasons, the Finally block is executed in two cases:

If the Finally block runs smoothly, the end of the entire try-catch-Finally block is "due to the reason R suddenly aborted (completes abruptly )".

If the Finally block is suddenly terminated due to the reason s, the end of the entire try-catch-Finally block is "Completes abruptly", and R will be discarded.

3.4 try-catch-return in the finally Block
From the execution process of the try-catch-Finally block and the execution result section above, we can see that finally will be executed no matter what happens in the try or catch, then the return statement written in try or catch won't actually jump out of the function. In this case, it becomes the control (statement flow) to the Finally block. In this case, pay attention to the processing of the return value.

For example, return false in try or catch, and return true in finally, in this case, do not expect the return value of return false in your try or catch to be obtained by the upper-level called function. The upper-level called function can only obtain the return value in finally, because the return statement in try or catch is only used to transfer control.

3.5 categories of exceptions

1.1
Inheritance structure of exceptions: The base classes include throwable, error, and exception, which inherit from throwable, runtimeexception, and ioexception. The specific runtimeexception inherits from runtimeexception.
1.2
Error, runtimeexception, and its subclass become unchecked, and other exceptions become checked ).
2. characteristics of each type of exception
2.1 Error System
The error class system describes internal errors in the Java running system and resource depletion. Applications should not throw such objects (usually thrown by virtual machines ). In addition to trying to secure the exit of the program, this error is not feasible in other aspects. Therefore, when designing programs, we should pay more attention to the exception system.
2.2 exception system
Exception systems include the runtimeexception system and other non-runtimeexception systems.
2.2.1 Runtimeexception
The runtimeexception system includes incorrect type conversion, array out-of-bounds access, and attempts to access null pointers. The principle for processing runtimeexception is: If runtimeexception occurs, it must be a programmer error. For example, you can check the array subscript and array boundary to avoid array out-of-bounds access exceptions.
2.2.2 Others (ioexception, etc)
This type of exception is generally an external error, for example, an attempt to read data from the end of a file. This is not a program error, but an external error in the application environment.
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.