Difficulties in Java Exception Handling Mechanism-use code to speak

Source: Internet
Author: User
Tags finally block

Difficulties in Java Exception Handling Mechanism-use code to speak
In the following example, what is the return value for normal execution? What is the return value if ArithmeticException occurs? What is the return value if a non-ArithmeticException (such as NullPointerException) occurs?
If you understand the problems described in this example and the execution details in three cases in this example, you don't have to waste time reading this article.
Example:

Public int testException_finally () {int x; try {x = 1; // int y = 1/0; // If you open this page, ArithmeticException occurs. /* // Comment out int y = 1/0;. Open it here and NullPointerException String str = null; str. substring (0); */return x;} catch (ArithmeticException e) {x = 2; return x ;}finally {x = 3 ;}}

Answer:
If execution is normal, the returned value is 1;
If ArithmeticException is thrown, the returned value is 2;
If other exceptions are thrown, the Exception is thrown and no return value is returned.

Let's see what you know. You do not need to read this article.
Let's continue with this article. Which of the following statements is right for you?

1. Java exception Classification

The Throwable class is the base class for all exceptions and errors in the Java language. Throwable has two direct subclasses: Error and Exception. Error is used to indicate the compilation period or system errors. Generally, we don't need to worry about it as a programmer (currently it's still a programmer, but is there a mind to be an architect ?); Exception is the basic type of exceptions that can be thrown. This is the base class that we need to care about.
The basic concept of Java exceptions during design is to use names to represent issues that occur. The names of exceptions should be well known. Exceptions are not all defined in the java. lang package. IO exceptions are defined in the java. io package. In Exception, there is an Exception: RuntimeException (runtime Exception) does not need to be caught in the program. Java will automatically catch this Exception. The Exception of RuntimeException and its subclass is added with an Error Exception, it is collectively referred to as unecked Exception (non-check Exception); Other exceptions and their subclass exceptions (excluding RuntimeException and its subclass exceptions) are collectively referred to as checked Exception (check Exception ). Check exceptions are the exceptions we need to capture and handle. Non-checked exceptions are automatically caught and thrown by Java. Of course, we can also take the initiative to catch RuntimeException exceptions. However, Error exceptions are generally not captured and handled.

2. Basic rules for Java Exception Handling

For Java code blocks that may encounter exceptions, we can put them in try {}, and then use catch (*** Exception e) {} After try to handle the specific exceptions thrown, if no matching catch exception is thrown, the exception will be thrown up to the next level until it is thrown to the Main () method.
There are some code that we want to execute no matter whether the code in the try operation is successful or failed. Then we can put the code in finally.
Java Exception Handling adopts the termination model, that is, if an exception occurs somewhere in the try block, the current program is immediately stopped and the corresponding exception object is created in the heap, exception Handling is transferred to the exception handling code (that is, the corresponding catch block). After the exception handling code is executed, the program after the exception occurs in the try block will not be executed, the program jumps out of the try block and executes programs other than the try block.
Example: overwrite knowledge points: ① execute the corresponding catch; ② execute the finally code; ③ do not execute the code after an exception occurs;

public String testException_one(){        String str = "aaa";        try {            str += "bbb";            int a = 1/0;            str += "ccc";        } catch (NullPointerException e) {            str += "ddd";        } catch (ArithmeticException e) {            str += "eee";        } finally {            str += "fff";        }        str += "ggg";        return str;    }

Result returned by the Program Execution: aaabbbeeefffggg
Note: ccc and ddd Are not output.
Result Analysis: The above program enters the try block, connects to bbb, and then encounters an ArithmeticException thrown by 1/0. First, the catch block where NullPointerException is located does not match the exception, check that the catch Block in which ArithmeticException is located matches the exception and enter the catch Block for exception handling. The finally block will be executed after the catch Block is executed, but the code after the try block reports an exception line will not be executed again, jump out of the try block and continue to execute try... Catch... Finally code.

3. Exception restrictions 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 () throws TwoException; void say () throws OneException;} class Person {public Person () throws TwoException {System. out. println ("Person Constructor... ");} public void eat () throws OneException {System. out. pr Intln ("Person eat... ");} public void say () throws TwoException {System. out. println ("Person say... ") ;}} public class Coder extends Person implements Worker {/*** TwoException is required because the Person constructor throws TwoException. * The Coder must also throw an exception when calling the parent class constructor and cannot be a subclass exception. In addition, the constructor can throw more exceptions than the parent class. * @ Throws TwoException * @ throws OneException */public Coder () throws TwoException, OneException {super ();} /*** the methods of the implemented interface or the methods of the overwritten parent class can throw an exception of the original method or its subclass exception or not throw an exception, * However, exceptions that are not declared by the original method cannot be thrown. In this case, the method of the base class is still valid when the subclass is transformed up to the base class execution method. */Public void work () throws TwoSonException {// TODO Auto-generated method stub}/*** this method is available in both the interface and parent class, if the exception declaration is not the same, the method declaration cannot throw any exception, * This method in the subclass must satisfy the exception requirements of its Implemented interfaces and inherited base classes at the same time during polymorphism. You cannot throw more exceptions than the declaration of the base class or interface method. */Public void say () {}/*** the eat method in the base class throws an exception. When this method is overwritten in the subclass, you can not declare to throw an exception */public void eat () {}}/**. You should also note that if the method declaration throws a RunTimeException type exception, it is not subject to the preceding restrictions; only check exceptions are subject to the preceding restrictions. Non-checked exceptions are not subject to any restrictions due to automatic system capture. **/
4. finally will certainly Execute

① Break/continue/while: as shown in the following example, if a continue or break is encountered in a loop, the finally statement will also be executed.

Public void testException_two () {for (int I = 0; I <5; I ++) {try {if (I = 0) {continue ;} if (I = 1) {throw new Exception () ;}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 return is executed normally in the try block, finally is executed before return. As shown in the following example:

Public void testException_three () {int a = 1; try {System. out. println ("try... "); return;} catch (Exception e) {// TODO: handle exception} finally {System. out. println ("finally... ") ;}}/* execution result: try... finally... */

③ Another case is that when a try block throws an exception, if no catch block can catch the exception, the exception will be thrown to the upper level. Before the exception is thrown to the upper level, the finally block will be executed, and then the exception will be thrown to the upper level. If you are interested, verify it by yourself.

In short, the finally code will be executed.

5. Exception in finally loss

Due to the special nature of finally, exceptions may be lost. if an exception is thrown in finally or return is used in finally, the exception thrown in the try block will be thrown away by the system. As shown in the following code (Definitions of OneException and TwoException are provided in the exception restriction section above ):

Public void testException_finally_one () {try {System. out. println ("test finally... "); try {if (1 = 1) {throw new OneException () ;}} finally {throw new TwoException () ;}} 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 new OneException () ;}} finally {return ;}} catch (Exception e) {System. out. println ("e. getClass: "+ e. getClass () ;}}/* execution result output: test finally... */
6. Confused returned values caused by finally

The following describes how to solve the problem at the beginning of this article.
Example:

Public int testException_finally () {int x; try {x = 1; // int y = 1/0; // If you open this page, ArithmeticException occurs. /* // Comment out int y = 1/0;. Open it here and NullPointerException String str = null; str. substring (0); */return x;} catch (ArithmeticException e) {x = 2; return x ;}finally {x = 3 ;}}

Answer:
If execution is normal, the returned value is 1;
If ArithmeticException is thrown, the returned value is 2;
If other exceptions are thrown, the Exception is thrown and no return value is returned.

Q: this is an example in my book titled deep understanding of Java Virtual Machine-advanced JVM features and best practices (P187 ~ P188. The cause of this situation is: If no exception occurs, x = 1 is executed first, and then return x is executed, first, save a copy of x in the local variable table of the method stack frame. Before performing return, perform the finally operation: x = 3; set the value of x to 3, however, in return, the copy of x stored in the local variable table is taken out and put to the top of the stack to return. Therefore, if no exception is thrown, the return value is 1. If an ArithmeticException exception or its subclass is abnormal, the return value is 2. If a non-ArithmeticException occurs, after x = 3 is executed, throws an exception to the first layer without returning a value.
If you are familiar with bytecode commands, you can use commands such as javap-verbose to decompile the bytecode commands and exception tables of this method. The execution process can be clearly seen from the bytecode level. I do not know enough about bytecode commands. I can only explain this process in general. In the future, when I learned how to use bytecode commands, I will also write articles related to bytecode. I hope this article will help some people Understand Java's exception handling mechanism.

 

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.