Finally is bound to execute (instance code)

Time:2019-3-23

As follows:


class Exc{
 int a;
 int b;
}
 
 
public class Except {
 @SuppressWarnings("finally")
 static int compute (){
 Exc e = new Exc();
 e.a = 10;
 e.b = 10;
 int res = 0 ;
 try{
  res = e.a / e.b;
  System.out.println("try ……");
  return res + 1;
  
 }catch(NullPointerException e1){
  System.out.println("NullPointerException occured");
 }catch(ArithmeticException e1){
  System.out.println("ArithmeticException occured");
 }catch(Exception e3){
  System.out.println("Exception occured");
 }finally{
  System.out.println("finnaly occured");
 }
 System.out.println(res);
  
 return res+3;
 }
 
 public static void main(String[] args){
 int b = compute();
 System.out.println("mian b= "+b);
 }
}

Output:


try ……
finnaly occured
mian b= 2

Conclusion:If there are no exceptions, the code block in try is executed until return in try, and then the code block in final is executed. After final execution, return is executed in try. Exit the function.


class Exc{
 int a;
 int b;
}
 
 
public class Except {
 @SuppressWarnings("finally")
 static int compute (){
 Exc e = new Exc();
// e.a = 10;
// e.b = 10;
 int res = 0 ;
 try{
  res = e.a / e.b;
  System.out.println("try ……");
  return res + 1;
  
 }catch(NullPointerException e1){
  System.out.println("NullPointerException occured");
 }catch(ArithmeticException e1){
  System.out.println("ArithmeticException occured");
 }catch(Exception e3){
  System.out.println("Exception occured");
 }finally{
  System.out.println("finnaly occured");
 }
 System.out.println(res);
  
 return res+3;
 }
 
 public static void main(String[] args){
 int b = compute();
 System.out.println("mian b= "+b);
 }
}

Output:


ArithmeticException occured
finnaly occured
0
mian b= 3

Conclusion:If there is an exception in try, jump to the block of exception code captured by catch at the exception statement. After execution of catch, execute last, jump out of try {} catch {} finally {} and continue to execute downward. The following statement in try will not be executed.

The above final article will be executed (example code) is the entire content shared by the editor, I hope to give you a reference, but also hope that you support more developpaer.