Order of execution for try{}catch{} and finally{} in Java

Source: Internet
Author: User

Today I will explain to you the Java error and exception handling mechanism and the execution order of related exceptions. If there are deficiencies, please criticize

1. The Prime Minister briefly describes the errors (error) and exceptions (Exception) in Java

Description of errors and exceptions:

There is a java.lang.Throwable class in the Java.lang package, which is a superclass of all errors and exceptions in Java.

There are two main errors and exceptions in Java: the error and the exception two respectively.

Error: Is the parent of all the wrong classes in Java, that is, the JVM error, and system crashes, such as the phenomenon, these errors can not be handled by the program, for system errors, generally do not need to develop

Personnel processing (also unable to process), such as memory overflow (out of memories). So it is necessary to use catch in the program to catch such errors or use throw to throw a phase

The exception that is closed.

Exception: can also be divided into checkedexception (compile-time exception) and RuntimeException (runtime exception) of the two exceptions, Checkedexception exception in the compilation of the

It is possible to know that there will be no exceptions, and if these exceptions are not thrown or caught, they cannot be compiled, such as when reading a file using Java IO, there may be

If the file being read does not exist, for such compile-time exceptions, they must be manually processed (captured or thrown). Otherwise, the compiler does not work correctly. and

RuntimeException is the exception that occurs when you are running, and you cannot determine whether an exception will occur before you. This type of exception is only found in the process of running the program.

For example, array subscript out of bounds (arrayindexoutofboundsexception), cast error (ClassCastException, part), NULL pointer exception (NULLPOINTEREXCEPTION)

The divisor is 0 (/by zero ) If the exception is thrown for this type of runtime, and the user decides whether to throw an exception, depending on the situation. Java does not force the user to be certain of processing.

2. Exception Handling Process

Put the exception of the program section in the try, when the exception is thrown in the system to generate an exception object, and then do a lookup to catch the exception, and then handle the exception, after processing and then execute the following program.

After an exception occurs, if no capture processing system is made, the tracking information of the exception stack is printed directly and the execution of the program is ended.

There are two ways to handle exceptions: try{}catch{}finally{} and throws the difference and connection between them.

Let's look at the following example:

public class test{public   static void Main (string[] args) {       Test2 test2 = new Test2 ();       try{          System.out.println ("Invoke the Method begin!");          Test2.method ();          System.out.println ("Invoke the Method end!");       } catch (Exception e) {          System.out.println ("Catch exception!");}}}   Class test2{Public   void Method () throws exception{       System.out.println ("Method begin!");       int a = ten;       int b = 0;       int c = A/b;       System.out.println ("Method end!");}   } Obviously, the answer is: Invoke the method Begin!method Begin!catch exception!

  

For try{}catch{}finally{}, the user may be determined to know that the code will be associated with an exception, place a possible problem in a try, and terminate the continuation of the current code if an exception occurs

execution, in turn to execute the contents of catch{}. For this type of exception the user has already handled it and will not throw it up.

For throws, it is generally used after the method name, when using the throws keyword, it is common for developers to be unsure of what is going on or if there are anomalies. The developer then throws the associated exception with the throws keyword after the method. Other developers who call the method must catch the exception or continue to throws the exception, passing the exception to the corresponding parent class for processing.

It is important to note that the throw keyword and the throws keyword are different. Throw is commonly used in methods, throwing user-defined exceptions such as throw new MyException ("User-defined exceptions").

The throws is used after the method name to notify the person using the method that the current method is likely to throw an exception.

If the simple understanding can be seen this way: for throws can be understood as thrown, thrown to others, themselves do not handle. try{}catch{}finally{} is understood to be truncated and the developer handles the exception itself.

3.execution order of exception handling (for try{}catch{}finally{})

For try{}catch{}finally{}, the order of execution is simple, if the corresponding exception is caught in try{}, the execution of the current code is interrupted, the contents of the catch{} are executed, and the final execution

finally{} method, in general, the method in the finally will be executed, in which finally is used to a large extent for the release of resources.

Here are some things that our Java programmers need to be aware of.

Is the code in a,finally always executed?

A: No, if a method is already return before executing the try{} statement, then the finally statement specifies that it will not execute. Because it did not enter the try statement at all

If you call System.exit (0) in a try statement, then you exit the current Java virtual machine, then finally there is no chance of execution.

b.does the finally execute before the return or after the return?

A: A lot of people might say that before the return is executed. My answer is to execute in the middle of return, is not very special, please follow the example below:

Package Com.yonyou.test;class test{public  static void Main (string[] args) {      System.out.println (method ());     } public  static int method () {  int x=1;  try{  return x;  } catch (Exception e)  {  return 0;  } finally{  ++x;}}}    

What is the result of the output, please?

The correct answer is: 1

Let me explain the implementation of this program,

First the program executes to the return method in the try{} statement, it returns the corresponding value and stores the corresponding value in a temporary stack to save the result. In this case, the value stored in the temporary stack is 1.

However, the program does not return immediately, and then go back to the method in the Finally, ++x, after the finally execution, the method is all finished, the return method will be called again, note that this time

is not the return value, but tells the main program, the program has been executed, you can go on to execute the other methods of your main program. Note, however, that the value returned at this time is still originally saved in the temporary

The value in the stack is 1.

To better understand the problem, let's look at the following procedure:

Package Com.yonyou.test;class test{public  static void Main (string[] args) {      System.out.println (method ());     } public  static int method () {  try{  return 1;  } catch (Exception e)  {  return 0;  } finally{  return 2;}}    }

What is the correct answer then?

Yes, 2, just note that executing to return 1 in the try{} statement stores a variable with a value of 1 in the staging stack. Then go back and execute the contents of Finally, then execute the return 2 in the Finally, and then

The value in the temporary stack is changed to 2, overwriting the value in the original temporary stack by 1. So it has a return value of 2.

C,The finally method is necessary?

No, developers can decide whether to use the Finally keyword, depending on their situation.

All right, let's get here today.

Order of execution for try{}catch{} and finally{} in Java

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.