Java异常处理机制以及try(2)

四,try-catch-finally-return执行顺序:

1,try-catch-finally执行顺序:

①,执行try{}块

②,如果try{}块有异常产生,执行catch{}块

③,无论有没有异常都要执行finally{}块,这里可以看出只要finally中有return,必然返回finally{}中的return


2,return的执行,

①,如果finally{}块中有return语句,只执行finally{}块中的return语句

②,如果finally{}块中没有return语句,如果try{}有异常,则返回catch{}中的return语句,不然执行try{}中return语句

在这种情况下,return语句块是在finally{}之后执行

finally{}中有return:

①如果try正常/或异常,则执行finally{}中的return

package com.testJava.Exception;
public class TryCatchfFinally {
public static void main(String[] args){
TryCatchfFinally tcf = new TryCatchfFinally();
System.out.println(tcf.testException());
}
public  String testException(){
try {
System.out.println("start try");
int[] a= {2};
for(int i=0 ; i<1;i++){//i=2①
System.out.println(a[i]);
}
System.out.println("try end");
return "return of try not finally";
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("arrayIndexOutOfBoundsException");
return "return in catch arrayIndexOutOfBoundsException";
}catch(NullPointerException e){

System.out.println("nullPointerException");
return "return in catch";

}finally{
System.out.println("finally start try");
int[] a= {2};
for(int i=0 ; i<1;i++){//i=2②
System.out.println(a[i]);
}
System.out.println("finallyend end  end");

System.out.println("finally");

return "return of finally";
}
}
}

①处i=1运行结果:

start try
2
try end
finally start try
2
finallyend end  end
finally
return of finally


①处i=2运行结果:

start try
2
arrayIndexOutOfBoundsException
finally start try
2
finallyend end  end
finally
return of finally

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/4d3d8bcfe7ed486c63f7695f25daa7a9.html