Java-try-catch-finally

Source: Internet
Author: User
Tags finally block try catch

The Try-catch statement can also include the third part, which is the finally clause. It represents what should be done regardless of whether an exception occurs. The general syntactic form of the try-catch-finally statement is:

Try {      //  may  occur exception program code catch  (Type1 id1) {      //  Capture and process the exception type thrown by the  try Type1catch  (Type2 id2      ) {//  Captures and handles the exception type thrown by the  try Type2finally  {      // The statement block  that will execute regardless of whether an exception occurred }  

The exception handler with the finally clause.

 Public classTestException { Public Static voidMain (String args[]) {inti = 0; String greetings[]= {' Hello world! ', ' Hello world! ',                  "HELLO World!!!" };  while(I < 4) {              Try {                  //pay special attention to the design of the cyclic control variable i to avoid causing infinite loopsSystem.out.println (greetings[i++]); } Catch(arrayindexoutofboundsexception e) {System.out.println ("Array subscript out-of-bounds exception"); } finally{System.out.println ("--------------------------"); }          }      }  }  

Operation Result:

Hello World!--------------------------!! --------------------------!!! --------------------------array Subscript out- of-bounds exception --------------------------

In Example 5, pay special attention to the design of the block of statements in the TRY clause, and if the design is as follows, a dead loop will occur. If the design is:

Try {        System.out.println (greetings[i]); I++  ;  }

Try block: used to catch an exception. You can then pick up 0 or more catch blocks, and if there is no catch block, you must follow a finally block.
Catch block: The exception that is used to handle a try catch.
Finally BLOCK: the statements in the finally block are executed regardless of whether the exception is caught or handled. When a return statement is encountered in a try block or catch block, the finally statement block is executed before the method returns. In the following 4 special cases, the finally block is not executed:

1) An exception occurred in the finally statement block. 2) exit the program with System.exit () in the previous code. 3) the thread on which the program is located dies. 4) Turn off the CPU.
try-catch-finally Rules ( syntax rules for exception-handling statements ):

1) You must add a catch or finally block after the try. The try block can be followed by a catch and finally block at the same time, but with at least one block.
2) The block order must be followed: If the code uses both catch and finally blocks, the catch block must be placed after the try block.
3) The Catch block is related to the type of the corresponding exception class.
4) a try block may have multiple catch blocks. If so, the first matching block is executed. That is, the Java Virtual Opportunity matches the exception type declared by each catch code block in turn, and if the exception object is an instance of an exception type or its subclass, the catch block is executed and no additional catch block is executed.
5) can be nested try-catch-finally structure.
6) in the try-catch-finally structure, the exception can be re-thrown.
7) In addition to the following cases, the total execution finally ends: the JVM terminates prematurely (call System.exit (int)), throws an unhandled exception in the finally block, the computer loses power, fires, or encounters a virus attack.

execution order of try, catch, finally statement blocks:

1) When the try does not catch an exception: the statement in the TRY statement block is executed by itself, the program skips the Catch statement block, executes the finally statement block and the subsequent statement;

2) When a try catches an exception, there is no case in the catch statement block that handles this exception: When an exception occurs in a statement in a try statement block, and there is no catch statement block that handles the exception, the exception is thrown to the JVM for processing, and the statement in the finally statement block is executed. But the statement after the finally statement block will not be executed;

3) When a try catches an exception, there is a case in the catch statement block that handles this exception: in the TRY statement block is executed in order, when the execution to a statement exception, the program jumps to the catch statement block, and the catch statement block one by one, to find the corresponding handler, The other catch statement blocks will not be executed, and the statement after the exception is not executed in the TRY statement block, after the catch statement block executes, the statement in the finally statement block is executed, and finally the statement after the final statement block is executed;

Test the finally execution impact situation

Does not affect the return result, mainly returned in the try, only after the finally, even if the name change does not affect the return result

     Public Static voidMain (string[] args) {System.out.println (Get ("")); }         Public Staticstring Get (string name) {Try{System.out.println ("Try X" +name); Name= Name.tolowercase () + "123456"; System.out.println ("Try Y" +name); returnname; } Catch(Exception e) {System.out.println ("Exception" +name); }finally{Name= "----"; } System.out.println ("Return" +name); return"```"; }

Results

Try x Try y123456123456

Can affect the return value (this column tests the same as if the object's reference is not the data of the base data type, and if the content in the object is changed in Finally, the contents of the return will also change, i.e. the character the object points to in memory)

     Public Static voidMain (string[] args) {System.out.println (Get (NewStringBuilder ()). ToString ()); }         Public StaticStringBuilder Get (StringBuilder name) {Try{System.out.println ("Try X" +name); Name.append ("123456"); System.out.println ("Try Y" +name); returnname; } Catch(Exception e) {System.out.println ("Exception" +name); }finally{name. Append ("-----"); } System.out.println ("Return" +name); returnname; }

Results

Try x Try y123456123456-----

A condition that affects the return value (primarily a return executed in finally) and is forced to affect the return in the try

     Public Static voidMain (string[] args) {System.out.println (Get ("")); }         Public Staticstring Get (string name) {Try{System.out.println ("Try X" +name); Name= Name.tolowercase () + "123456"; System.out.println ("Try Y" +name); returnname; } Catch(Exception e) {System.out.println ("Exception" +name); }finally{Name= "----"; System.out.println ("Finally" +name); return"This column"; }        //System.out.println ("return" +name); //return "'";}

Output (it is obvious from the result that the original return of 123456 is returned by the finally return)

Try x Try y123456 finally---- this column

Java-try-catch-finally

Related Article

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.