In-depth understanding of Java abnormal processing mechanism

xiaoxiao2021-03-06  40

1 group

Try ... catch ... finaLY is probably a statement that everyone is familiar with, and it feels very simple, logically seems to be easy to understand. However, I personally experience the "lesson" tells me that this thing is not as simple as imagined, obedient. Do not believe? Then you look at the following code, "Guess" what is the result after the execution? Don't look back in the answer, you don't want to perform code to see the true answer. If your answer is correct, then this article you don't have to waste time.

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 = FalseteSteSteSteStestex1, Catch Exception

TESTEX1, FINALLY; RETURN VALUE = FALSE

TESTEX, CATCH EXCEPTION

TESTEX, FINALLY; RETURN value = false

If your answer is really as mentioned above, then you are wrong. ^ _ ^, Then I suggest you look at this article or take the above code to modify, execute, test, execute, test, you will find that there are many things that are not as simple as it is.

Now announce the correct answer:

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 Related Concepts

Exception is an exception event that occurs during the program run, such as in addition to 0 overflow, array offline, file could not find, etc., these events will block the normal operation of the program. In order to enhance the robustness of the program, the program is designed to take into account the possible abnormal events and make corresponding processing. In the C language, by using the IF statement to determine whether there is an exception, the calling function is performed by the returned value of the called function perceive the exception event generated in the modified function. The full variable Errono is often used to reflect the type of an exception event. However, this error handling mechanism will cause a lot of problems.

Java handles exceptions by object-oriented methods. During a method, if an exception has occurred, this method generates an object representing the exception and handles it to the runtime system, running the corresponding code to handle this exception. We use an exception to generate exception objects and submit it to the runtime system is called a detailed (throw). The runtime system looks up in the call stack of the method, starting back from generation to generation, until the method containing the corresponding exception processing is found, this process is called capture (CATCH) an exception.

2.2 Throwable class and their subclasses

Treatment with object-oriented methods must establish levels of classes. Class Throwable is the top level of this class, only its descendants can be discarded as an exception. Figure 1 shows the class level of exception processing.

As can be seen from the figure, class throwable has two direct subclasses: Error and Exception. Error class objects (such as dynamic connection errors, etc.), generated by Java virtual machines (usually, Java programs do not process such exceptions); Exception class object is an object of Java program or abandonment. It has a variety of different subclasses corresponding to different types of exceptions. The class RuntimeException represents the exception of the Java virtual machine generated by the runtime, such as arithmetic operation exceptions arraysXception (resulting in 0 error), array-proofexoutofboundsexception, etc .; others are non-runtime exceptions, such as input and output exceptions IOEXCEPTION. The Java compiler requires the Java program to capture or declare all non-run exceptions, but can do not work outside the runtime exception.

Figure 1 Except for class level

2.3 Exception Processing Keywords

Java's exception handling is achieved by 5 keywords: Try, Catch, Throw, Throws, Finally. JB's online help is explained in this way:

THROWS: LISTS The Exceptions a Method Could 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 sentence

The TRY statement specifies a piece of code with braces {}, which may abandon one or more exceptions.

2.3.2 Catch statement

The parameters of the CATCH statement are similar to the declaration of the method, including an exception type and an exception object. The exception type must be a subclass of the Throwable class, which indicates the exception type processed by the CATCH statement. Exception objects are generated by the runtime system in the code block specified by TRY and captured, and the braces contain objects, whereby The method of the object can be called.

The CATCH statement can have multiple exceptions to different classes, respectively. The Java runtime system detects the exception type of each Catch statement process from top to bottom, until the type matched CATCH statement is found. Here, the type matching refers to the exception type of the exception to the CATCH is identical to the type of the exception object or its parent class, so the order of the Catch statement should be from special to general.

Multiple exception types can also be processed with a CATCH statement. At this time, it should be the multi-exceeded parent class, and the program is designed to select the exception processing 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 specify a piece of code through a Finally statement. Regardless of whether TRY is discarded or not discarded, whether the code specified by Finally is executed regardless of whether the exception type of the CATCH statement is consistent with the type of exceptions abandoned, the code specified by Finally is executed. It provides a unified export. The resource can be cleared in the Finally statement. If you turn it off, the file, etc., etc.

2.3.4 THROWS statement

Throws always appears in a function header to indicate the various exceptions that the member function may thrown. For most Exception subclasses, the Java compiler will force you to declare the type of abnormality thrown in a member function. If the type of abnormality is Error or RuntimeException, or their subclasses, this rule does not work because it is not expected in the normal part of the program. If you want to clearly 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 be terminated immediately after the throw statement, and the following statement is not executed, and then in all the TRY blocks containing it (possibly in the upper-layer call function), the TRY block containing the CATCH clause that matches thereof.

3 Keywords and explanations

3.1 TRY Nested

You can write a TRY statement outside in a member function, in this member function, write another TRY statement to protect other code. Whenever you encounter a try statement, the unusual framework is placed on the stack until all TRY sentences are completed. If the TRY statement of the next level does not process some anomalies, the stack will be expanded until the TRY sentence with this exception is encountered. Here is an example of a TRY statement nested.

Class Multinest {

Static void procedure () {TRY {

INT A = 0;

INT B = 42 / A;

} 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 result of this example is:

In Procedure, Catch ArithmeticException: java.lang.arithmeticException: / by Zero

There is your own TRY / CATCH control in the member function Procedure, so MAIN does not have to deal with ArrayIndexoutofboundSexception; of course, if you start with the example of testing, use the throw E when catching Catch to exceptions, the statement will throw an exception, then Main Of course, it is still able to capture and process an exception thrown out of this procedure. For example, after the system.out statement in the Catch of the Procedure function, the execution result changes to:

In Procedure, Catch ArithmeticException: java.lang.arithmeticException: / by Zero

In Main, Catch Exception: java.lang.arithmeticException: / by Zero

3.2 TRY-CATCH block execution process and execution result

The execution process of try-catch is still relatively simple relative to the try-catch-finally block.

First, the statement in the TRY statement block is executed, and there may be the following three cases:

1. If all statements in the TRY block are performed normally, then there will be no other "motion" is executed, and the entire TRY-CATCH program block is completed.

2. If the TRY sentence block encounters an exception V during the execution process, it is divided into two situations:

2 If the abnormality V can be cafate with TRY Catch block Catch, then the first Catch to this exception Catch block (also a Catch block that matches the most recent V-matching of TRY) will be executed; if the Catch block is executed properly The result of the try-catch block is "normally completed"; if the Catch block suddenly suspended due to the cause R, the result of the TRY-CATCH block block is "due to facts abruptly".

2 If the exception V does not match it, then the result of this try-catch block is "completes abruptly" due to throwing exception V.

3. If TRY is suddenly aborted due to other reasons R, then the result of this try-catch block is "due to facts abruptly".

3.3 The execution process of the try-catch-finally program block and the execution process of the try-catch-finally block and the execution result are more complicated.

First, the statement in the TRY statement block is executed, and there may be the following three cases:

1. If all the statements in the TRY block are completed normally, the Finally block will be executed, and the following two situations are divided into the following:

2 If the Finally block performs smooth, the entire try-catch-finally program block is done normally.

2 If the Finally block is suddenly suspended due to the reason R, the ending of the try-catch-finally block is "due to facts abruptly"

2. If the TRY sentence block encounters an exception V during the execution process, it is divided into two situations:

2 If the abnormal V can be Catch block catch with TRY, the first Catch to this exception Catch block (also a Catch block that matches the most recent V-match) of TRY will be executed; at this time there will be Two kinds of execution results:

2 If the Catch block is executed normally, the Finally block will be executed, and it is divided into two cases:

2 If the Finally block performs smooth, the entire try-catch-finally program block is done normally.

2 If the Finally block is suddenly suspended due to the reason R, the ending of the try-catch-finally block is "due to facts abruptly"

2 If the Catch block suddenly stops due to the reason R, the Finally module will be executed and divided into two situations:

2 If the Finally block performs smooth, the ending of the entire try-catch-finally block is "due to the cause R suddenly abort" ".

2 If the Finally block suddenly stops due to the reason, the ending of the entire Try-Catch-Finally block is "due to facts abruptly", the reason R will be abandoned.

(Note, here is just in line with our example, although we throw an exception in Testex2, but because there is a finally block in TESTEX2, the result of the Finally block is Complete Abruptly (don't look at this It is also one of the reasons why Complete Abruptly, which leads to the cause analysis of Complete Abruptly, so the result of the entire try-catch-finally block is "Complete Abruptly", so Testex1 is called TESTEX2 to capture the exception thrown in TESTEX1, but can only get the return result in Finally.

If you expect to give a return value by capturing an exception to be called by capturing, then pay attention to the finally statement in the lower-level function you call, it may make the exception of your throw can't be truly Visible by the superior call function. Of course, this situation can be avoided, taking TESTEX2 as an example: If you must use Finally and to capture the THROW in the catch in TESTEX1, then you remove Return in the finally in TESTEX2. This thing has appeared in the MIB of OMC2.0: the exception of the server cannot be fully fed back to the client. )

2 If the exception V does not match the catch block, the Finally module will be executed and divided into two situations:

2 If the Finally block performs smooth, the ending of the entire try-catch-finally block is "completes abruptly" due to the throwing exception V.

2 If the finally block is suddenly suspended, the ending of the entire try-catch-finally block is "due to facts abruptly", the exception V will be abandoned.

3. If TRY is suddenly aborted due to other reasons, the FinalLy block is executed and divided into two situations:

2 If the Finally block is successfully performed, the ending of the entire try-catch-finally block is "due to the reason R suddenly abort" ".

2 If the Finally block suddenly stops due to the reason, the ending of the entire Try-Catch-Finally block is "due to facts abruptly", the reason R will be abandoned.

3.4 Return in the try-catch-finally block

From the execution process of the Try-catch-finally block, the implementation result section can be seen in the trory or catch, FINALLY is executed, then written in TRY or CATCH RETURN statement It will not be truly jumped from this function. Its role becomes in this case into the FINALLY block in this case; in this case, it must pay attention to the processing of the return value.

For example, Return False in Try or Catch, and Return True in Finally, then in this case, don't expect your TRY or CATCH Return False's return value FALSE to be obtained by the top-level call function, the superior call function can The obtained return value in Finally, because the Return statement in TRY or CATCH is only the function of transfer control.

3.5 How to throw an exception

If you know that a function you write is likely to throw an exception, you don't want to process an exception in this function, just want to throw it out to process the superior call function to call this function, then there are two kinds Way to choose from:

The first way: THROWS SomeException directly in the function header, does not require TRY / CATCH in the function body. For example, the TESTEX2 in the first example is changed to the following manner, then 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;

}

Second: Use try / catch to throw some exception after a certain process is performed in catch (if necessary). For example, TESTEX2 is changed to the following manner, TESTEX1 can also capture the exceptions throwing:

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;

}

}

Third way: Use try / catch / finally to throw some anomalies after a certain process is performed in the catch (if necessary). For example, TESTEX2 is changed to the following manner, TESTEX1 can also capture the exceptions throwing:

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

The front mentioned Complete Abruptly (temporarily understood "or" anomaly end "), it mainly contains two large situations: Abrupt Completion of Expressions and Statements, the following is interpreted.

4.1 Normal and Abrupt Completion of Evaluation

Each expression (Expression) has a normal mode that makes it included in step by step, and if each step is performed and there is no abnormality, then this expression is "completion normally" If the calculation of this expression throws an exception, it is called an "Complete Abruptly". An abnormally ends usually have a associated reason, which is usually throwing an exception V.

With expressions, operational periods related to operators are exception:

² 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.

2 A field access throws a nullpointerexception if the value of the object reference refression is null.

2 a Method Invocation Expression That Invokes An Instance Method throws a NullPointers IS NULL.

2 An Array Access Throws a NullpointersException if The value of the array reference expression is null.

2 an arrayxoutofboundsexception if the value of the array ion INDEX Expression is negative or greater tresions.

2 a cast throws a classcastexception if a cast is found to be impermissible at run time.

2 An Integer Division or Integer RemainDer THROWS An ArithmeticeXception if The value of the right-hand operand expression is Zero.

2 An assignment to an array component of reason at Types 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

Normally, we don't have much to say, it is mainly to list several situations: Abrupt Completion:

2 Break, Continue, And Return statement will result in conversion of control, so that STATEMENTS does not perform normally, completely.

2 Some expressions can also throw an exception from the Java virtual machine, which has been summed up in the previous section; an explicit THROW statement will also cause an exception to thrown. Throwing anomalies are also the causes of conversion of control (or the reason for blocking the normal end of Statement).

If the above event occurs, then these statements may make the statements that should be performed under normal circumstances cannot be completely executed, then these statements are also called COMPLETE ABRUPTLY.

Several reasons leading to Abrupt Completion: 2 A Break with no label

2 A Break with a given label

2 a Continue with no label

2 A Continue with a given label

2 a returnid with no value

2 a return with a Given Value a

2 throw with a given value, including Exceptions thrown by the java virtual machine

5 suggestions about our programming

We can use it correctly after the implementation of try-catch-finally.

If we use the try-catch-finalty statement, and we need to guarantee an exception when there are abnormalities, then do not use the return statement in the finally statement (the most important role of the Finally statement should be released application Resources because the return statement in Finally causes our throw e to be abandoned, and the return value in the Finally (unless an exception is thrown in FINALLY) outside this try-catch-finally. (We need to remember: not only the throw statement is the reason, Return, Break, Continue, etc. It seems that a normal statement is also the cause of Abrupt Completion.)

转载请注明原文地址:https://www.9cbs.com/read-51315.html

New Post(0)