1. Conclusion is given. :

(1) Whether there is an anomaly or not ,finally All the code in the block will execute ;
(2) When try and catch There is return when ,finally Still execute ;
(3)finally Is in return The following expression is evaluated ( The calculated value is not returned , Instead, save the value you want to return , tube finally What about the code in , The value returned will not change , It's still the value that we saved before ), So the return value of the function is at finally Determined before execution ;
(4)finally It is best not to include return, Otherwise the program will exit early , The return value is not try or catch The return value saved in .

give an example :

situation 1:try{} catch(){}finally{} return;
           Obviously the program runs in sequence .

situation 2:try{ return; }catch(){} finally{} return;
          Program execution try In block return Before ( Include return Expression operations in statements ) Code ;
          Re execution finally block , Finally, execute try in return;
          finally Statement after block return, Because the program is try Already in the return So no more execution .

situation 3:try{ } catch(){return;} finally{} return;
          Program first try, If an exception is encountered catch block ,
           There are abnormal : execute catch in return Before ( Include return Expression operations in statements ) Code , Re execution finally All the code in the statement ,
                      Finally, execute catch In block return. finally After that 4 The code at .
           No abnormality : After execution try Again finally Again return.

situation 4:try{ return; }catch(){} finally{return;}
          Program execution try In block return Before ( Include return Expression operations in statements ) Code ;
          Re execution finally block , because finally In the block return So exit early .

situation 5:try{} catch(){return;}finally{return;}
          Program execution catch In block return Before ( Include return Expression operations in statements ) Code ;
          Re execution finally block , because finally In the block return So exit early .

situation 6:try{ return;}catch(){return;} finally{return;}
          Program execution try In block return Before ( Include return Expression operations in statements ) Code ;
          There are abnormal : perform catch In block return Before ( Include return Expression operations in statements ) Code ;
                        Is to perform finally block , because finally In the block return So exit early .
          No abnormality : Is to perform finally block , because finally In the block return So exit early .

The final conclusion

Any implementation try perhaps catch Medium return The statement before , Will execute first finally sentence , If finally exist . If finally There is return sentence , So the program is return 了 , therefore finally Medium return Is bound to be return Of , The compiler the finally Medium return Implemented as a warning.

2.  In at least two cases finally Statements are not executed :

(1)try The statement is not executed to , If in try The statement before return And back , such finally Statement will not execute , It also shows that finally The necessary but not sufficient condition for a statement to be executed is : Corresponding try The statement must be executed until .

(2) stay try In the block System.exit(0); Such a statement ,System.exit(0); Is termination Java virtual machine JVM Of , even JVM It's all stopped , It's all over , Of course finally Statements are not executed to .

-->1. The case is as follows :

 package com.himi.finallydemo;
public class FinallyDemo2 {
public static void main(String[] args) {
System.out.println(getInt()); } public static int getInt() {
int a = 10;
try {
System.exit(0);
System.out.println(a / 0);
a = 20; } catch (ArithmeticException e) {
a = 30;
// return a;
} finally {
a = 40;
} return a;
} }

The operation effect is as follows :

above getInt() In the method , Execute first int a = 10; And then execute try sentence , Discovery begins with System.exit(0), So virtual machines jvm immediate withdrawal , Of course, it doesn't print any information .

-->2. The case is as follows :

 package com.himi.finallydemo;
public class FinallyDemo2 {
public static void main(String[] args) {
System.out.println(getInt()); } public static int getInt() {
int a = 10;
try {
System.out.println(a / 0);// After execution , Jump straight to the second 17 That's ok
System.exit(0);
a = 20; } catch (ArithmeticException e) {
a = 30;
// return a;
} finally {
a = 40;
} return a;
} }

Run the following effect :

Here it is try Execute in statement System.out.println(a / 0), The system will immediately catch the exception and execute it directly catch sentence , And then execute finally sentence , Last return a

( here a yes 40)

-->3. Case study :

 package com.himi.finallydemo;
public class FinallyDemo2 {
public static void main(String[] args) {
System.out.println(getInt()); } public static int getInt() {
int a = 10;
try {
System.out.println(a / 0);
System.exit(0);
a = 20; } catch (ArithmeticException e) {
a = 30;
return a;
/*
* return a At this point in the program , It's not here return a It is return 30; This return path forms .
* But what? , It found that there was finally, So keep going fianlly The content of ,a=40
* Return to the previous return path again , Continue to go return 30;
*/
} finally {
a = 40;
//return 40;// If so, the result is 40
} return a;
} }

The operation effect is as follows :

Java Strengthen the basic knowledge IO Stream notes 06: Yes return Under the circumstances try catch finally More articles on the execution order of

  1. Java Strengthen the basic knowledge IO Stream notes 17:FileOutputStream The construction method uses

    1. You can refer to the previous notes :   Android(java) Learning notes 167:Java Class introduction of operation file in (File + IO flow ) 2. FileOutputStream( frequently-used ) Construction method : FileOu ...

  2. Java Strengthen the basic knowledge IO Stream notes 83:NIO And IO

    When learning Java NIO and IO Of API after , A question immediately came to mind : When should I use IO, When to use NIO Well ? In this paper , I'll try to be as clear as I can Java NIO and IO The difference of . Their usage scenarios , And how they affect your generation ...

  3. Java Strengthen the basic knowledge IO Stream notes 71:NIO And NIO Of (New IO flow ) Introduce

    1. I/O brief introduction I/O ( Input / Output  ): The interface between a computer and the outside world or between a program and the rest of the computer . It is very important for any computer system , So all I/O The main body of is actually built into the operating system . ...

  4. Java Strengthen the basic knowledge IO Stream notes 68:Properties and IO Stream sets use

    1. Properties and IO Stream sets use The set here has to be Properties aggregate :  public void load(Reader reader): Reading data from a file into a collection  public v ...

  5. Java Strengthen the basic knowledge IO Stream notes 66:Properties Overview and Use ( As Map Use together )

    1. Properties Overview   Properties: Property collection class . It's a person who can communicate with IO Collection classes used in combination with streams . This class is mainly used to read the configuration file of the project ( With .properties Final document and xml file ). ...

  6. Java Strengthen the basic knowledge IO Stream notes 41: Character stream buffer stream copy text file case 02( Use [ newLine() / readLine() ] )( important )

    1. Use the special function of character stream buffer stream [ newLine() / readLine() ] demand : Put... In the current project directory a.txt Copy the content to... In the current project directory b.txt in   data source : a.txt -- Reading data ...

  7. Java Strengthen the basic knowledge IO Stream notes 39: Character stream buffer stream copy text file case 01

    1.  Character stream buffer stream copy text file case demand : Put... In the current project directory a.txt Copy the content to... In the current project directory b.txt in data source : a.txt -- Reading data -- Character conversion stream -- InputStreamRe ...

  8. Java Strengthen the basic knowledge IO Stream notes 38: Character stream buffer stream BufferedWriter / BufferedReader Use

    1.  Character stream buffer stream : Character stream for efficient read and write , The corresponding character buffer stream is also provided . BufferedWriter: Character buffered output stream BufferedReader: Character buffered input stream 2. BufferedWriter Use ...

  9. Java Strengthen the basic knowledge IO Stream notes 37:FileReader/FileWriter( Subclass of transformation flow ) Copy text file case

    1. A simplified way to write a conversion stream : Because our common operation is to use the local default encoding , therefore , You don't have to specify the encoding . And the name of the transformation stream is a little long , therefore ,Java It provides subclasses for us to use :FileReader / FileWriterOut ...

Random recommendation

  1. python Find all the files in the specified directory , And how to change the file name

    One : os.listdir(path) hold path All the files in the directory are saved in the list : >>> import os>>> import re>>> pa ...

  2. Magento- Find products without pictures

    Recently maintain the website , Found that many of the products of the website are not shown in pictures , I took a look because I didn't check the picture in the background , Namely image small_image  thumbnail These three items , Even if there is a picture, if it is not checked, it will not be displayed , product ...

  3. spring Common annotations use parsing

    spring There is no policy of convention over configuration ,spring It is required to show the paths under which to search Java file .spring Will put the right java All classes are registered as spring Bean.   problem :spring How do you know what to put ...

  4. An exception occurred during a WebClient request

    System.Net.WebException was caught HResult=-2146233079 Message=An exception occurred during a WebCli ...

  5. Modify in wechat title

    // need jQuery.zepto edition function weixinTitle(){ var $body = $('body'); document.title = 'title'; // hack In micro ...

  6. 【 turn 】 When partitioning a hard disk ,GPT and MBR difference .

    stay Windows 8 or 8.1 When setting a new disk in , The system will ask you if you want to use MBR still GPT Partition .GPT It's a new standard , And it's gradually replacing MBR. GPT It brings a lot of new features , but MBR Still have the best compatibility .GPT Not at all W ...

  7. C#winform Call in wpf( turn )

    stay WinForm You can use WPF Control in ( Or by WPF Custom control created ) 1. Create a new one winform project : 2. Create a new one on the solution wpf project : Pictured : If there are the following errors , It's just winform Reference in ...

  8. find a filename from a filehandle in Perl

    my $filename='/tmp/tmp.txt';open my $fh, '>', $filename;my $fd = fileno $fh;print readlink(" ...

  9. 【 original 】POJ 1703 && RQNOJ Energy Necklace problem solving report

    alas Don't want to say anything poj 1703, From reading the title to writing the first version of the code , Only 15 minute And then all the way from eight in the evening WA By the next morning Finally I found out BUG, The title requires “Not sure yet.”, I got it “No s ...

  10. Unity C# note coroutines

    What is a journey Collaborative process , While the main program is running , Open another logic processing , To coordinate the execution of the current program . Maybe it's a little fuzzy after reading this passage , In fact, we can use multithreading to compare . Multithreading Multithreading , seeing the name of a thing one thinks of its function , Multiple simultaneous threads . first ...