Java Exception Handling Mechanism (try... Catch... Finally)

Source: Internet
Author: User
Tags integer division

1 Guide
Try... Catch... Finally is probably 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.
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.2 throwable 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.
It can be seen that the throwable class 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.
 

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.1 try statement
The try statement specifies a piece of code with braces {}, which may discard one or more exceptions.
2.3.2 catch 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.5 throw 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.1 try 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 try, then the first catch block to this exception (also the Catch Block closest to try that matches the exception v) will be executed. If the Catch Block is executed normally, the result of the try-Catch Block is "normal completion". If the Catch Block is suddenly terminated due to the reason 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" because an exception V is thrown )".
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 runs smoothly, 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 "caused by the reason 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 try, then the first catch to the exception Catch Block (also the Catch Block closest to try that matches the exception 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 runs smoothly, 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 "caused by the reason R is suddenly aborted (completes abruptly )"
--> If the Catch Block is suddenly terminated due to 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 that r suddenly stops (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 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.
3. 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 that r suddenly stops (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 how can I throw an exception?
If you know that a function you write may throw an exception, and you do not want to handle the exception in this function, you just want to throw it to let the upper-level calling function that calls this function handle it. There are two options:
Method 1: throws someexception directly in the function header, and try/catch is not required in the function body. For example, change testex2 in the initial example to the following method, so testex1 can capture the exception thrown by testex2.
Boolean testex2 () throws exception {
Boolean ret = true;
Int B = 12;
Int C;
For (INT I = 2; I >=- 2; I --){
C = B/I;
System. Out. println ("I =" + I );
}
Return true;
}
Method 2: Use try/catch to throw an exception after some processing (if necessary) in catch. For example, if testex2 is changed to the following method, testex1 can also catch the exception thrown by it:
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 ");
Throw E;
}
}
Method 3: Use try/catch/finally to throw an exception after some processing (if necessary) in catch. For example, if testex2 is changed to the following method, testex1 can also catch the exception thrown by it:
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 );
Throw new exception ("AAA ");
}
Return true;
} Catch (Java. Lang. arithmeticexception e ){
System. Out. println ("testex2, catch exception ");
Ret = false;
Throw new exception ("AAA ");
} Finally {
System. Out. println ("testex2, finally; return value =" + RET );
}
}
4 about abrupt completion
As mentioned above, complete abruptly (for the moment, it can be understood as "sudden stop" or "Abnormal End") mainly involves two major situations: abrupt completion of expressions and statements, the following two cases are explained.
4.1 normal and abrupt completion of evaluation
Each expression has a normal mode that allows the computation contained in it to proceed step by step. If each computation is executed and no exception is thrown, this expression is called "complete normally". If an exception is thrown during calculation of this expression, it is called "complete abruptly )". There is usually an associated reason (associated reason) for the end of an exception, which is usually to throw an exception v.
Runtime exceptions related to expressions and operators include:
--> A class instance creation expression, array creation expression, or String concatenation operatior expression throws an outofmemoryerror if there is insufficient memory available.
--> An array creation expression throws a negativearraysizeexception if the value of any dimension expression is less than zero.
--> A field access throws a nullpointerexception if the value of the Object Reference expression is null.
--> A Method Invocation expression that invokes an instance method throws a nullpointerexception if the target reference is null.
--> An array access throws a nullpointerexception if the value of the array reference expression is null.
--> An array access throws an arrayindexoutofboundsexception if the value of the array index expression is negative or greater than or equal to the length of the array.
--> A cast throws a classcastexception if a cast is found to be impermissible at run time.
--> An integer division or integer remainder operator throws an arithmeticexception if the value of the right-hand operand expression is zero.
--> An assignment to an Array Component of reference type throws an arraystoreexception when the value to be assigned is not compatible with the component type of the array.
4.2 normal and abrupt completion of statements
We will not talk much about the normal situation. Here we mainly list several situations of abrupt completion:
--> The break, continue, and return statements will convert the control, so that statements cannot be executed properly and completely.
--> Some expressions may also throw exceptions from the Java Virtual Machine. These expressions have been summarized in the previous section. An explicit throw statement will also throw exceptions. Throwing an exception is also the cause of control conversion (or the reason that the statement ends normally ).
If the above events occur, these statement statements may make it impossible to fully execute all statements normally. These statement statements are called complete abruptly.
Several causes of abrupt completion:
--> A break with no label
--> A break with a given label
--> A continue with no label
--> A continue with a given label
--> A return with no value
--> A return with a given value
--> Throw with a given value, including exceptions thrown by the Java Virtual Machine
5. Some suggestions on our programming
We can use the try-catch-finally command correctly only after the execution of try-catch-finally is clear.
If we use a try-catch-Finally block, and we need to ensure that an exception can be thrown when an exception occurs, in the finally statement, do not use the return statement (the most important role of the finally statement block is to release the requested resource ), because the return statement in finally will cause our throw e to be discarded, the return value in finally can only be seen outside this try-catch-finally (unless an exception is thrown in finally ). (We need to remember that not only throw statements are the cause of abrupt completion, but return, break, continue and other seemingly normal statements are also the cause of abrupt completion .)

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.