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

如果finally{}中没有return,

如果try{}正常,执行try{}return语句,如果异常执行catch{}中return语句,但是此事return语句返回在finally{}语句之后

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++){//①
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++){//②
System.out.println(a[i]);
}
System.out.println("finallyend end  end");

System.out.println("finally");

//return "return of finally";
}
//return "end fuction";
}
}


①处i=1运行结果:

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


①处i=2运行结果:

start try
2
arrayIndexOutOfBoundsException
finally start try
2
finallyend end  end
finally
return in catch arrayIndexOutOfBoundsException


-----------------------------------------------------------------------------------------------------

finally{}中有错误,应该是直接退出

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

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