黑马程序员_JAVA中异常处理机制

------Java培训、Android培训、iOS培训、.Net培训、期待与您交流! -------

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值