In this article we will introduce the use of try, Catch, finally in Java

Try and catch:

Try {// Exception code to be detected}Copy the code
Catch (Exception e) {//Copy the code
Finally {// the code that must be executed}Copy the code

If there is an error in the code area, processing of the exception that was written is returned.

First, be aware that without a try, an exception will cause the program to crash. A try ensures that the program runs properly, for example:

try
{
    int i = 1/0;
}
catch(Exception e)
{
    ........
}
Copy the code

An error will be reported if the divisor is 0, and the program will crash if there is no try. With try, you can run the program and say why it failed!

Try catch is catching an Exception in the try part, so when you don’t have a trycatch, if you get an Exception, you get an error, trycatch, you get an Exception, it works fine, it just stores the error information in the Exception, so the catch is used to get the Exception, You can add system.out.println (e.tostring ()) to the catch section; If there is an exception, you can print the exception ~~

 

Java’s exception handling mechanism (try… The catch… finally)

1 the introduction

The try… The catch… Finally is probably a very familiar statement, and it feels very simple to use and seems logically easy to understand. However, my personal experience has taught me that this thing is not as simple and obedient as it seems. Don’t believe it? Take a look at the code below and “guess” what the result will be after it is executed. Don’t look behind the answer, and don’t run code to see the real answer. If your answer is correct, then you don’t need to waste your time reading this article.

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

What’s your answer? Is it the following answer?

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
Copy the code

If your answer is true, you are wrong. Take a look at this article carefully or use the above code to modify, implement, and test in various situations. You will find that many things are not as easy as you thought. Now 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
Copy the code

2 Basic Knowledge

2.1 Related Concepts

Exceptions are abnormal events that occur during the running of the program, such as division by 0 overflow, array out of bounds, file cannot be found, etc., which will prevent the normal running of the program. In order to enhance the robustness of the program, the possible abnormal events must be considered and dealt with accordingly during the program design. In C language, an if statement is used to determine whether an exception occurs. At the same time, the calling function senses the exception event generated in the called function through the return value of the called function and processes it. The global variable ErroNo is often used to reflect the type of an exception event. However, this error handling mechanism can cause a number of problems. Java handles exceptions through an object-oriented approach. If an exception occurs during the execution of a method, the method generates an object representing the exception and hands it to the runtime system, which looks for code to handle the exception. We call the process of generating an exception object and submitting it to the runtime system throwing an exception. The runtime system looks through the call stack of methods, starting with the method that generated the exception and working backwards until it finds a method that contains the corresponding exception handling. This process is called catching an exception.

2.2 Throwable class and its subclasses

To handle exceptions in an object-oriented way, you must establish a hierarchy of classes. Throwable is at the top of this hierarchy, and only its descendants can be discarded as an exception. Figure 1 shows the class hierarchy of exception handling. As you can see from the figure, the class Throwable has two direct subclasses: Error and Exception. Error class objects (such as dynamic connection errors) that are generated by the Java virtual machine and thrown away (Java programs generally do not handle such exceptions); Exception class objects are objects that Java programs process or discard. It has various subclasses corresponding to different types of exceptions. One kind of RuntimeException representing run-time exceptions generated by the Java virtual machine, such as arithmetic exception ArithmeticException (caused by zero fault, etc), an array exception ArrayIndexOutOfBoundsException, etc; Others are non-runtime exceptions, such as I/O exception AND IOException. The Java compiler requires Java programs to catch or declare all non-runtime exceptions, but runtime exceptions can be left alone.

2.3 Keywords of Exception Handling

Java exception handling is implemented with five keywords: try, catch, throw, throw, finally. Throws: Lists the exceptions a method could throw. Throw: Transfers control of the method to the exception handle. Try: Opening exception-handling statement. Catch: Captures the exception. Finally: Runs its code before terminating the program.

2.3.1 the try

The try statement uses curly braces {} to specify a piece of code that may discard one or more exceptions.

2.3.2 catch statement

The parameters of a catch statement are similar to method declarations and include an exception type and an exception object. The exception type must be a subclass of the Throwable class. It specifies the type of exception handled by the catch statement. The exception object is generated and captured by the runtime system in the block of code specified by try. There can be more than one catch statement, handling exceptions of different classes. The Java runtime system checks each exception type handled by a catch statement from top to bottom until it finds a catch statement that matches the type. Here, type matching means that the type of exception handled by a catch is exactly the same as the type of the generated exception object or is its parent. Therefore, the order of catch statements should be from special to general. A catch statement can also be used to handle multiple exception types. In this case, its exception type parameter should be the parent of the multiple exception types. In the program design, the exception handling type of the catch statement should be selected according to the specific situation.

2.3.3 finally statement

When an exception is discarded in the code qualified by a try, no subsequent code is executed. A finally statement allows you to specify a block of code. Code specified by finally is executed whether an exception is discarded or not in the block specified by try, and whether the exception type of the catch statement matches the type of the discarded exception. It provides a uniform exit. Resource cleaning is usually done ina finally statement. Close open files.

2.3.4 throws statement

Throws Always appears in a function header and identifies the various exceptions that the member function may throw. For most Exception subclasses, the Java compiler forces you to declare the type of Exception thrown in a member function. This rule does not work if the exception type is Error or RuntimeException, or a subclass of them, because this is not expected in the normal part of the program. If you want to throw a RuntimeException explicitly, you must declare its type with the throws statement.

2.3.5 throw statement

A throw is always present in the body of a function and is used to throw an exception. The program terminates immediately after the throw, fails to execute any statement that follows it, and then looks inside out of all the try blocks that contain it (perhaps in the upper calling function) for any catch clause that matches it.

3 Key words and their statement process

3.1 Nesting of tries

You can write a try statement outside of a member function call, and another try statement inside that member function to protect other code. Each time a try statement is encountered, the exception frame is put on the stack until all tries are complete. If the next level of try does not handle an exception, the stack expands until it encounters a try statement that does. Here is an example of a nested try statement.

1 class MultiNest { 2 static void procedure() { 3 try { 4 int a = 0; 5 int b = 42/a; 6 } catch(java.lang.ArithmeticException e) { 7 System.out.println("in procedure, catch ArithmeticException: " + e); 8 } 9 } 10 public static void main(String args[]) { 11 try { 12 procedure(); 13 } catch(java.lang. Exception e) { 14 System.out.println("in main, catch Exception: " + e); 15} 16} 17}Copy the code

The result of this example execution is:

in procedure, catch ArithmeticException: java.lang.ArithmeticException: / by zero
Copy the code

 

The member function PROCEDURE has its own try/catch control, so main does not handle ArrayIndexOutOfBoundsExc

Eption; Of course, if we use throw e in the PROCEDURE when we catch an exception, as we did in the original test example; The procedure statement throws an exception, and of course Main can catch and handle the exception thrown by the PROCEDURE. For example, add throw E after the system. out statement in the CATCH of the PROCEDURE function; After the statement, the result of the execution becomes:

in procedure, catch ArithmeticException: java.lang.ArithmeticException: / by zero
in main, catch Exception: java.lang.ArithmeticException: / by zero
Copy the code

3.2 Execution flow and result of try-catch program block

Compared to a try-catch-finally block, the try-catch process and its results are relatively simple. The statement in the try block is executed first, where one of the following situations may occur: 1. If all statements in the try block execute normally, then no other action is executed and the entire try-catch block completes normally. 2. If V can be caught by a block corresponding to the try, the first catch (which is also the closest catch to V) will be executed. If the catch block executes properly, the result of the try-catch block is “normal completion”; If the catch block suddenly aborted due to cause R, the try-catch block would result in “suddenly aborted due to cause R (ease-abruptly)”. –> The result of the try-catch block would be “abrupt abort due to the throwing of an exception V (ease-abruptly)” if no catch block matched the exception V. 3. The result of this try-catch block would be “suddenly aborted due to cause R (ease-abruptly)” if the try aborted suddenly for some other reason, R (ease-abruptly).

3.3 Execution process and result of the try-catch-finally program block

The execution process and result of try-catch-finally program block are complicated. The statement in the try block is executed first, where one of the following situations may occur: 1. A try-catch-finally block is executed if all statements in the finally block are executed properly. In this case, the try-catch-finally block is executed properly. –> A try-catch-finally block will end with “ease-of-r (abruptly)” if the finally block suddenly aborts due to cause R. (at abruptly) If V can be caught by a block corresponding to the try, the first catch (which is also the closest catch to V) will be executed. There are two possible results: if the catch block executes properly, then the finally block is executed: if the finally block executes successfully, then the entire try-catch-finally block completes properly. –> If the finally block suddenly aborts due to cause R, the try-catch-finally block will end with “ease-r (ease-abruptly)” –> If the catch block suddenly aborts due to cause R, the finally module will be executed. In two cases: –> The try-catch-finally block will end in “an abrupt halt due to R (ease-abruptly)” if the finally block executes successfully. –> If the finally block suddenly aborts due to cause S, then the entire try-catch-finally block will end with “suddenly aborted due to cause S (ease-abruptly)” and cause R will be discarded. TestEx2: finally (finally) {return: complete abruptly} testEx2: finally (finally) {return: complete abruptly It is also one of the causes of complete abruptly — there is an analysis of the causes of complete abruptly), so the whole try-catch-finally block results in “Complete abruptly”, So a call to testEx2 from testEx1 does not catch the exception thrown from testEx1, but only returns from finally. If your code expects a return value to be given by catching the exception of the called function, be careful about the finally statement in the function you call. It may make the exception you throw invisible to the calling function. Of course, this can be avoided. Take testEx2 for example: If you must use finally and you want the catch throw e to be caught in testEx1, you can simply remove the return in finally from testEx2. This has already happened in the MIB of OMC2.0: server exceptions cannot be fully reported to the client. –> If exception V does not match a catch block, the finally module will be executed in two cases: –> If the finally block executes successfully, the try-catch-finally block will end up with “an abrupt abort due to an exception V (ease-abruptly)”. –> If the finally block suddenly aborts due to cause S, then the whole try-catch-finally block will end with “suddenly aborted due to cause S (ease-abruptly)”, and the exception V will be discarded. 3. In the event that R suddenly aborts for some other reason (ease-abruptly), the finally block is executed, in two cases: –> If the finally block executes successfully, the try-catch-finally block will end in “abrupt abort due to R (ease-abruptly)”. –> If the finally block suddenly aborts due to cause S, then the entire try-catch-finally block will end with “suddenly aborted due to cause S (ease-abruptly)” and cause R will be discarded. As you can see from the try-catch-finally execution flow and results section above, the finally is executed no matter what happens in the try or catch. A return statement written ina try or catch does not actually exit the function. In this case, it transfers control (the flow of the statement) to the finally block. In this case, be careful how you handle the return value. For example, if you return false ina try or catch and then return true in finally, do not expect the return false of your try or catch to be retrieved by the calling function. All the calling function can get is the return value in finally, because the return statement ina try or catch only transfers control. 3.5 How to Throw An Exception If you know that you are writing a function that may throw an exception, and you do not want to handle the exception in this function, you just want to throw it out and let the superior calling function handle it, then there are two ways to do this: Throws SomeException directly in the function header. No try/catch is required in the function body. For example, if testEx2 in the original example is changed to the following way, testEx1 will catch the exception thrown by testEx2.

1 boolean testEx2() throws Exception{ 2 boolean ret = true; 3 int b=12; 4 int c; 5 for (int i=2; i>=-2; i--){ 6 c=b/i; 7 System.out.println("i="+i); 8 } 9 return true; 10}Copy the code

The second way is to use try/catch and throw some kind of exception after some processing in the catch, if necessary. For example, if testEx2 above is changed to the following way, testEx1 can also catch the exception it throws:

1 boolean testEx2() throws Exception{ 2 boolean ret = true; 3 try{ 4 int b=12; 5 int c; 6 for (int i=2; i>=-2; i--){ 7 c=b/i; 8 System.out.println("i="+i); 9 } 10 return true; 11 }catch (Exception e){ 12 System.out.println("testEx2, catch exception"); 13 Throw e; 14}} 15Copy the code

The third method: use try/catch/finally to throw some kind of exception after some processing ina catch, if necessary. For example, if testEx2 above is changed to the following way, testEx1 can also catch the exception it throws:

1 boolean testEx2() throws Exception{ 2 boolean ret = true; 3 try{ 4 int b=12; 5 int c; 6 for (int i=2; i>=-2; i--){ 7 c=b/i; 8 System.out.println("i="+i); 9 throw new Exception("aaa"); 10 } 11 return true; 12 }catch (java.lang.ArithmeticException e){ 13 System.out.println("testEx2, catch exception"); 14 ret = false; 15 throw new Exception("aaa"); 16 }finally{ 17 System.out.println("testEx2, finally; return value="+ret); 18}} 19Copy the code

4. The abrupt completion

The aforementioned complete abruptly (interpreted as “abrupt completion of Expressions” or “abnormal completion”) contains two major scenarios: the abrupt completion of Expressions and statements, which are explained in two different ways.

4.1 Normal and Abrupt Completion of Evaluation

Expression every normally expression has a normal pattern in which the computation it contains takes place step by step. If every other computation is performed and no exception is thrown, the expression is called “complete normally”. If the evaluation of this expression throws an exception, it is called “complete abruptly”. There is usually an associated reason for the exception to end, usually by throwing an exception V. Run-time exceptions associated with expressions and operators are: –>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

The normal case is not discussed too much, but there are several conditions of the Abrupt completion listed here: –>break, continue, and return statements will result in a transfer of control that makes statements unable to execute normally and completely. The evaluation of certain expressions, which were summarized in the previous section, may also throw exceptions from the Java virtual machine; An explicit throw statement also causes an exception to be thrown. Throwing an exception is also what causes the control transition (or prevents the statement from ending properly). If one of the above events occurs, then the statement may not be fully executed as it would normally be executed. The statement is called complete abruptly. Several reasons leading to an 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 A –>throw with a given value, including exceptions thrown by the Java virtual machine

Let’s look at an example (example 1) to illustrate the process of trying, catching, and finally in Java

1 public class TryCatchFinally { 2 3 @SuppressWarnings("finally") 4 public static final String test() { 5 String t = "";  6 7 try { 8 t = "try"; 9 return t; 10 } catch (Exception e) { 11 // result = "catch"; 12 t = "catch"; 13 return t; 14 } finally { 15 t = "finally"; 16 } 17 } 18 19 public static void main(String[] args) { 20 System.out.print(TryCatchFinally.test()); 21} 22 23}Copy the code

First, the program executes the try statement, assigning the variable t to try. Since no exception is found, it executes the finally statement, assigning the variable t to finally, and then returning t. The value of t is finally. But the actual result is try. To see why this is the case, let’s first look at the bytecode corresponding to the class compiled by this code to see how it is executed inside the virtual machine.

We use javap-verbose TryCatchFinally to display the object file (.class file) bytecode information

Operating environment: MAC OS Lion 64-bit

The JDK information: Java(TM) SE Runtime Environment (Build 1.6.0_29-B11-402-11m3527) Java HotSpot(TM) 64-bit Server VM (build 20.4-b02-402, mixed mode)

We will only look at the test method for some of the compiled bytecode information and ignore the rest

 1 public static final java.lang.String test();
 2   Code:
 3    Stack=1, Locals=4, Args_size=0
 4    0:    ldc    #16; //String 
 5    2:    astore_0
 6    3:    ldc    #18; //String try
 7    5:    astore_0
 8    6:    aload_0
 9    7:    astore_3
10    8:    ldc    #20; //String finally
11    10:    astore_0
12    11:    aload_3
13    12:    areturn
14    13:    astore_1
15    14:    ldc    #22; //String catch
16    16:    astore_0
17    17:    aload_0
18    18:    astore_3
19    19:    ldc    #20; //String finally
20    21:    astore_0
21    22:    aload_3
22    23:    areturn
23    24:    astore_2
24    25:    ldc    #20; //String finally
25    27:    astore_0
26    28:    aload_2
27    29:    athrow
28   Exception table:
29    from   to  target type
30     8    13   Class java/lang/Exception
31     8    24   any
32    19    24   any
33   LineNumberTable: 
34    line 5: 0
35    line 8: 3
36    line 9: 6
37    line 15: 8
38    line 9: 11
39    line 10: 13
40    line 12: 14
41    line 13: 17
42    line 15: 19
43    line 13: 22
44    line 14: 24
45    line 15: 25
46    line 16: 28
47 
48   LocalVariableTable: 
49    Start  Length  Slot  Name   Signature
50      27      0    t       Ljava/lang/String;
51      10      1    e       Ljava/lang/Exception;
52 
53   StackMapTable: number_of_entries = 2
54    frame_type = 255 /* full_frame */
55      offset_delta = 13
56      locals = [ class java/lang/String ]
57      stack = [ class java/lang/Exception ]
58    frame_type = 74 /* same_locals_1_stack_item */
59      stack = [ class java/lang/Throwable ]
Copy the code

So let’s look at the LocalVariableTable information, and there are two variables that are defined: one is of type T String and one is of type E Exception

Now look at the Code section

Line [0-2], assign “” to the 0th variable, i.e. String t=””;

Lines [3-6] execute the try block assignment, i.e. T = “try”;

Line 7, the point is line 7, pays the value of “try” for s to the third variable, but the third variable in this is not defined, which is kind of weird

At line [8-10], assign to the 0th variable, t=”finally”

Line [11-12] returns the corresponding value of the third variable

In the return block of the try statement, the reference variable returned by return (t is the reference type) is not the reference variable t defined outside the try statement. Instead, the system redefines a local reference t ‘, which refers to the value corresponding to the reference T, namely, try. Even if t points to the value finally ina finally statement, the return reference to t is not t, so the value that refers to t is irrelevant to the return value in the try statement.

 

Here’s an example :(example 2)

1 public class TryCatchFinally { 2 3 @SuppressWarnings("finally") 4 public static final String test() { 5 String t = "";  6 7 try { 8 t = "try"; 9 return t; 10 } catch (Exception e) { 11 // result = "catch"; 12 t = "catch"; 13 return t; 14 } finally { 15 t = "finally"; 16 return t; 17 } 18 } 19 20 public static void main(String[] args) { 21 System.out.print(TryCatchFinally.test()); 22} 23 24}Copy the code

This is a slight modification of the first code by adding a return t expression inside the finally block.

We do a try{} statement, then save the current value of t to a variable t’ before returning, and then execute a finally statement block to change the value of t and return t.

There are two return statements, but whether the program returns a try or finally. Next, let’s look at the bytecode information

1 public static final java.lang.String test(); 2 Code: 3 Stack=1, Locals=2, Args_size=0 4 0: ldc #16; //String 5 2: astore_0 6 3: ldc #18; //String try 7 5: astore_0 8 6: goto 17 9 9: astore_1 10 10: ldc #20; //String catch 11 12: astore_0 12 13: goto 17 13 16: pop 14 17: ldc #22; //String finally 15 19: astore_0 16 20: aload_0 17 21: areturn 18 Exception table: 19 from to target type 20 9 9 Class java/lang/Exception 21 16 16 any 22 LineNumberTable: 23 line 5: 0 24 line 8: 3 25 line 9: 6 26 line 10: 9 27 line 12: 10 28 line 13: 13 29 line 14: 16 30 line 15: 17 31 line 16: 20 32 33 LocalVariableTable: 34 Start Length Slot Name Signature 35 19 0 t Ljava/lang/String; 36 6 1 e Ljava/lang/Exception; 37 38 StackMapTable: number_of_entries = 3 39 frame_type = 255 /* full_frame */ 40 offset_delta = 9 41 locals = [ class java/lang/String ] 42  stack = [ class java/lang/Exception ] 43 frame_type = 70 /* same_locals_1_stack_item */ 44 stack = [ class java/lang/Throwable ] 45 frame_type = 0 /* same */Copy the code

The bytecode translated from this code is completely different from the first code, so keep looking at the code attribute

The first block of code in lines [0-2] and [3-5] initializes t and assigns t to try

At line 6, skip to line 17. [17-19] Executes the assignment in finally, assigning t to finally and returning the corresponding value of t

We find that the return statement in the try statement is ignored. The JVM probably thinks that having two return statements ina method doesn’t make much sense, so it ignores the return statement in try and finally.

 

Let’s look at a more complicated example :(example 3)

1 public class TryCatchFinally { 2 3 @SuppressWarnings("finally") 4 public static final String test() { 5 String t = "";  6 7 try { 8 t = "try"; 9 Integer.parseInt(null); 10 return t; 11 } catch (Exception e) { 12 t = "catch"; 13 return t; 14 } finally { 15 t = "finally"; 16 // System.out.println(t); 17 // return t; 18 } 19 } 20 21 public static void main(String[] args) { 22 System.out.print(TryCatchFinally.test()); 23} 24 25}Copy the code

Inside this try statement would be thrown inside the Java. Lang, a NumberFormatException, so the program will implement the logic in catch statement first, t assignment to catch, before the return, the return value is saved to a temporary variable t ‘inside, Execute finally logic. T is assigned to finally, but the return value is t’, so the value of the variable t is no longer related to the return value. Catch is returned

Example 4:

1 public class TryCatchFinally { 2 3 @SuppressWarnings("finally") 4 public static final String test() { 5 String t = "";  6 7 try { 8 t = "try"; 9 Integer.parseInt(null); 10 return t; 11 } catch (Exception e) { 12 t = "catch"; 13 return t; 14 } finally { 15 t = "finally"; 16 return t; 17 } 18 } 19 20 public static void main(String[] args) { 21 System.out.print(TryCatchFinally.test()); 22} 23 24}Copy the code

This is similar to example 2. Because the try statement throws an exception, the program passes into a catch statement block. The catch statement executes finally before the return statement

Example 5:

1 public class TryCatchFinally { 2 3 @SuppressWarnings("finally") 4 public static final String test() { 5 String t = "";  6 7 try { 8 t = "try"; 9 Integer.parseInt(null); 10 return t; 11 } catch (Exception e) { 12 t = "catch"; 13 Integer.parseInt(null); 14 return t; 15 } finally { 16 t = "finally"; 17 //return t; 18 } 19 } 20 21 public static void main(String[] args) { 22 System.out.print(TryCatchFinally.test()); 23} 24 25}Copy the code

This example adds integer.parser (NULL) to the catch block to force an exception. Then there is no return statement in the finally statement block. Because the try statement throws an exception, the program enters the catch statement block, which throws an exception, indicating that the catch statement is about to exit, the finally statement block is executed and t is assigned. Then the catch block throws an exception. The result is thrown Java. Lang. A NumberFormatException anomalies

Example 6:

1 public class TryCatchFinally { 2 3 @SuppressWarnings("finally") 4 public static final String test() { 5 String t = "";  6 7 try { 8 t = "try"; 9 Integer.parseInt(null); 10 return t; 11 } catch (Exception e) { 12 t = "catch"; 13 Integer.parseInt(null); 14 return t; 15 } finally { 16 t = "finally"; 17 return t; 18 } 19 } 20 21 public static void main(String[] args) { 22 System.out.print(TryCatchFinally.test()); 23} 24 25}Copy the code

The only difference in this example is that the finally statement contains a return block. The logic running ina try catch is the same as in the above example. When an exception is thrown in the catch block, finally is entered and t is returned. The program ignores the exception thrown in the catch block and returns the value of t, finally. Method does not throw an exception

Example 7:

1 public class TryCatchFinally { 2 3 @SuppressWarnings("finally") 4 public static final String test() { 5 String t = "";  6 7 try { 8 t = "try"; 9 Integer.parseInt(null); 10 return t; 11 } catch (NullPointerException e) { 12 t = "catch"; 13 return t; 14 } finally { 15 t = "finally"; 16 } 17 } 18 19 public static void main(String[] args) { 20 System.out.print(TryCatchFinally.test()); 21} 22 23}Copy the code

This example catch statement inside the catch of NPE is abnormal, not Java. Lang. A NumberFormatException is unusual, so will not enter the catch block, directly into the finally blocks, and finally to s assignment, Thrown by the try statement Java. Lang. A NumberFormatException anomalies.

Example 8:

1 public class TryCatchFinally { 2 3 @SuppressWarnings("finally") 4 public static final String test() { 5 String t = "";  6 7 try { 8 t = "try"; 9 Integer.parseInt(null); 10 return t; 11 } catch (NullPointerException e) { 12 t = "catch"; 13 return t; 14 } finally { 15 t = "finally"; 16 return t; 17 } 18 } 19 20 public static void main(String[] args) { 21 System.out.print(TryCatchFinally.test()); 22} 23 24}Copy the code

As in the try catch example above, the try statement completes by executing a finally statement, finally assigns s and returns S, and finally returns the program result

Example 9:

 1 public class TryCatchFinally {
 2 
 3     @SuppressWarnings("finally")
 4     public static final String test() {
 5         String t = "";
 6 
 7         try {
 8             t = "try";return t;
 9         } catch (Exception e) {
10             t = "catch";
11             return t;
12         } finally {
13             t = "finally";
14             String.valueOf(null);
15             return t;
16         }
17     }
18 
19     public static void main(String[] args) {
20         System.out.print(TryCatchFinally.test());
21     }
22 
23 }
Copy the code

In this example, we add string.valueof (NULL) to finally statements to force an NPE exception. First, the program executes a try statement. After the return execution, the finally statement block is executed. Finally throws an NPE exception.

Summarize all of the examples above

1 In a try, catch, and finally statement, if a try statement has a return statement, the value of the variable in the current try is returned. Any subsequent changes to the variable do not affect the return value in the try

2 If there is a return statement ina finally block, the return statement ina try or catch is ignored.

3 If an exception is thrown ina finally block, the entire try, catch, and finally block throws an exception

So here’s the caveat when using try, catch, finally blocks

1 Try to use return statements in a try or catch. It is not possible to modify the return value of a try or catch via a finally block.

2 Avoid using a return statement in the finally block. If a return statement is used in the finally block, exception information in the try and catch blocks will be digested and errors will be shielded

3. Avoid throwing an exception in the finally block. Otherwise, the entire method containing the try block will throw an exception back and digest the exceptions in the try and catch blocks

A bit of advice about our programming

We can use the try-catch-finally properly only after we know how it works. If we are using a try-catch-finally statement, and we need to be able to throw an exception, then we should not use a return statement in the finally statement (the primary purpose of a finally statement is to release requested resources). Because a return statement in finally causes our throw E to be discarded, only the return value in finally will be seen outside the try-catch-finally (unless an exception is thrown in finally). (It is important to remember that not only is the throw statement responsible for the abrupt completion, but also the return, break, continue, and other normal-looking statements that lead to the abrupt completion.)