Do you need to read this article?
In the following example, what is the return value if normal execution? What if the ArithmeticException return value appears? If a non-arithmeticexception (such as NullPointerException) is present, what is the return value?
If you understand the problem illustrated by this example and understand the details of the execution of the three cases in the example, you won't have to waste your time reading this article.
Example:
public int testexception_finally () {int x; try {x = 1 ; //int y = 1/0; Let go of here, and there arithmeticexception. /*//comment out int y = 1/0; Place, Release here, nullpointerexception String str = null appears; Str.substring (0); */ return x; } catch (ArithmeticException e) {x =2 ; return x; } finally {x = 3 ; } }
Answer:
if performed normally, the return value is 1;
If ArithmeticException is thrown, the return value is 2;
If another exception is thrown, the exception is thrown, with no return value.
A look on the students who know, scattered it. You don't need to read this article.
Unintelligible classmates, please continue to look down. Is it right for you to say the following?
1. Classification of Java Exceptions
The Throwable class is the base class for all exceptions and errors in the Java language. There are two direct subclasses of Throwable: Error and exception. Error is used to indicate compile time or system error, generally do not need our programmer care (now or program ape, but there is a heart to be an architect); exception is the basic type of exception that can be thrown, and this is the base class we need to be concerned about.
Java exception in the design of the basic idea is to use the name to represent the problem occurred, the name of the exception should be able to look at the text to understand. Exceptions are not all defined in the Java.lang package, as IO exceptions are defined in the Java.io package. In exception, there is an exception: RuntimeException (runtime exception) does not need to be specifically captured in the program, Java will automatically catch this kind of exception, RuntimeException and its subclass exception plus error exception, is called unecked Exception (non-check exception), other Exception and its subclass exceptions (excluding RuntimeException and their subclass exceptions), are uniformly called checked Exception (check-type exception). For a check-type exception, we need to catch and handle the exception. Non-checked exception Java is automatically captured and thrown. Of course, we can also proactively capture runtimeexception-type anomalies. But error-type exceptions generally do not capture processing.
2. Basic rules for Java exception handling
For a Java block of code that could have an exception, we could put it in try{} and then use catch (***exception e) {} After the try to handle the specific exception that was thrown, and if there were no matching catch handling exceptions, the exception would be thrown up one level. Until the main () method is thrown.
There is some code that we want to execute regardless of whether the code in the try is successful or failed, so we can put this code in finally{}.
Java exception handling is the termination model, that is, if there is an exception somewhere in the try block, immediately stop the current program running, create the corresponding exception object in the heap, the exception processing to the exception handling code (that is, the corresponding catch block), after executing the exception handling code, After an exception occurs in the try block, the program will not be executed, and the program will jump out of the try block and execute a program other than the try block.
Example: Overriding the knowledge point: ① executes the corresponding Catch;② must execute finally in the code, ③try the exception after the code is no longer executed;
PublicString Testexception_one () {stringStr="AAA";Try{Str+="BBB";intA =1/0;Str+="CCC"; }Catch(NullPointerException e) {Str+="DDD"; }Catch(ArithmeticException e) {Str+="Eee"; }finally{Str+="FFF"; }Str+="GGG";return Str; }
Program execution return Result: AAABBBEEEFFFGGG
Note: There is no output of CCC and DDD.
Results analysis: The above program entered the try block, connected to the BBB, and then encountered 1/0 throws ArithmeticException exception, first nullpointerexception in the catch block does not match the exception, Then check that the catch block where the ArithmeticException is located matches the exception and go inside the catch block for exception handling. After executing the catch block, the finally block must be executed, but the code after the try block reports the exception line will no longer execute, jump out of the try block, and continue executing the code after try...catch...finally.
3. Exception limitations when inheriting and implementing interfaces
class oneexception extends Exception{} class twoexception extends Exception{} class onesonexception extends oneexception{} class twosonexception extends twoexception{}interface Worker {void work ()throwsTwoexception; void Say ()throwsOneexception;} class person {Public person ()throwstwoexception {System.out.println ("Person Constructor ..."); } public void Eat ()throwsoneexception {System.out.println ("Person eat ..."); } public void Say ()throwstwoexception {System.out.println ("person say ..."); }}public class coder extends person implements Worker { /** * Twoexception here is required because twoexception is thrown in the constructor of person. * Coder when calling a parent class constructor, you must also throw a secondary exception, and it cannot be a subclass exception. In addition, constructors can throw more exceptions than the parent class. * @throws twoexception * @throws oneexception * *Public Coder ()throwsTwoexception, Oneexception {Super(); }/** * The method of implementing an interface or overriding a method of the parent class can throw an exception of the original method or its subclass exception or not throw an exception, * but cannot throw an exception that is not declared by the original method. This is for polymorphism, where the base class method is still valid when the subclass is transformed upward into a base class execution method. */public void work ()throwstwosonexception {//TODO auto-generated method stub}/** * This method is available in both the interface and the parent class, and the exception declaration is not the same exception, the declaration of the method cannot throw any exception, because the method in the subclass must satisfy both the interface it implements and the exception requirements of the inherited base class when it is polymorphic. You cannot throw more exceptions than a base class or an interface method declaration. */public void Say () {}The eat method in the/** * base class throws an exception, and when overridden in a subclass, it can not declare an exception thrown /public void Eat () {}}/** It should also be noted that if a method declaration throws an exception of type runtimeexception, it is not subject to the above limitation, and only the check-type exception is subject to the above limitation. Non-checked exceptions are automatically captured by the system and are not subject to any restrictions. **/
4. Finally, it will be executed
①break/continue/while: Finally also executes when continue or break is encountered in the loop as shown in the following example.
Public void Testexception_two(){ for(inti =0; I <5; i++) {Try{if(i = =0){Continue; }if(i = =1){Throw NewException (); }if(i = =3){ Break; } System. out. println ("Try ..."+ i); }Catch(Exception e) {System. out. println ("Catch ..."+ i); }finally{System. out. println ("Finally ..."+ i); } } }/* Execution Result: finally ... 0catch ... 1finally ... 1try ... 2finally ... 2finally ... 3 * /
②return: Even if the return,finally is executed normally in a try block, it is executed before the return. As shown in the following example:
publicvoidtestException_three(){ int1; try { System.out.println("try..."); return; catch (Exception e) { // TODO: handle exception finally{ System.out.println("finally..."); } } /*执行结果:try...finally... */
③ There is also the case that when a try block throws an exception, if no catch block catches the exception, the exception is thrown to the upper level, and the finally block is executed before being thrown to the upper level, and then the exception is thrown to the first level. This invites interested students to verify it yourself.
In summary, the code in the finally is bound to be executed.
5. Missing exception in finally
Because of the particularity of Finally, it also causes the exception to be lost, if an exception is thrown in finally or a return is used in finally, the exception thrown in the try block will be discarded by the system. As shown in the following code (the definitions of oneexception and twoexception are given in the above exception limit section):
Public void Testexception_finally_one(){Try{System. out. println ("Test finally ...");Try{if(1==1){Throw NewOneexception (); } }finally{Throw NewTwoexception (); } }Catch(Exception e) {System. out. println ("E.getclass:"+ E.getclass ()); } }/* * Execution result output: Test finally...e.getclass:class com.synnex.demo.TwoException */ Public void Testexception_finally_two(){Try{System. out. println ("Test finally ...");Try{if(1==1){Throw NewOneexception (); } }finally{return; } }Catch(Exception e) {System. out. println ("E.getclass:"+ E.getclass ()); } }/* Execute result output: Test finally ... */
6. Finally caused by the return value confusion
Let's go to the first example of this article.
Example:
public int testexception_finally () {int x; try {x = 1 ; //int y = 1/0; Let go of here, and there arithmeticexception. /*//comment out int y = 1/0; Place, Release here, nullpointerexception String str = null appears; Str.substring (0); */ return x; } catch (ArithmeticException e) {x =2 ; return x; } finally {x = 3 ; } }
Answer:
if performed normally, the return value is 1;
If ArithmeticException is thrown, the return value is 2;
If another exception is thrown, the exception is thrown, with no return value.
A: This is what I did with the example in the second edition of the Advanced features and best practices for understanding Java Virtual Machine-JVM (p187~p188). This occurs because, in the absence of an exception, the x=1 is executed first, then the return x is executed, and the first copy of X is saved in the local variable table of the method stack frame, and the action in the finally must be performed before the return: x=3; Set the value of X to 3 , but return takes the copy of the x saved in the local variable table and puts it back at the top of the stack. Therefore, the return value is 1 when there is no exception, the return value is 2 when the arithmeticexception exception or its subclass exception is present, and if a non-arithmeticexception exception occurs, the exception is thrown to the previous level and there is no return value when the x=3 is executed.
A friend who is familiar with bytecode commands can use commands such as javap-verbose to decompile the bytecode command and the exception table of the method, which clearly shows the execution process from the byte-code level. I don't know enough about bytecode commands to be able to explain this kind of running process in general. After the bytecode command learned to think that it is possible, it will also write a byte-code related article out. Hopefully this article will help some people understand the Java exception handling mechanism.
Reference articles and books:
An in-depth study and analysis of Java anomalies
"Java Programming thought" fourth edition Chinese version 12th chapter through exception handling error
"Deep understanding of Java Virtual Machine-JVM advanced features and best practices" the second edition of the sixth class file structure Zhou Zhiming
Java exception handling mechanism--talking in code