try-catch-finally与return的执行顺序

本文深入探讨了Java中try-catch-finally与return语句的执行顺序,通过具体测试案例展示了return语句的位置对程序执行流程的影响,并得出结论:try-catch-finally必须连在一起中间不能有语句,且return语句只能放在finally块的后面或最后。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

      写java程序经常碰到异常,try-catch-finally与return的执行顺序不是很清晰,总是调整到编译通过就放在那里了,没有细致的研究过,碰到的次数多了,很烦!

      测试一下(一):只有try-catch return语句在try里面。javac Test.java编译时报错:缺少返回语句。

    return语句放在catch后面,成功。


public class Test{
public static void main(String args[]){
System.out.println(a());	
}
private static String a(){
try{
				//throw new Exception();
	System.out.println("In TRY");
	return "返回值";
}catch(Exception e){
System.out.println("In Catch");

}
				//finally{
				//System.out.println("In FINALLY");
				//return "返回值";
				//}
				//System.out.println("Afer finally In Return");

}

}

     测试二:


public class Test{
public static void main(String args[]){
System.out.println(a());	
}
private static String a(){
try{
				//throw new Exception();
	System.out.println("In TRY");
	return "返回值";
}catch(Exception e){
System.out.println("In Catch");

}
finally{
System.out.println("In FINALLY");

}
				//System.out.println("Afer finally In Return");
return "返回值";
}

}

 结果:

   In TRY

   In FINALLY

返回值

   测试(三):return在finally前面,编译报错finally不带有try块。


public class Test{
public static void main(String args[]){
System.out.println(a());	
}
private static String a(){
try{
				//throw new Exception();
	System.out.println("In TRY");
	return "返回值";
}catch(Exception e){
System.out.println("In Catch");

}
return "返回值";
finally{
System.out.println("In FINALLY");

}
				//System.out.println("Afer finally In Return");

}

}

 测试(四):返回值在finally块里面:


public class Test{
public static void main(String args[]){
System.out.println(a());	
}
private static String a(){
try{
				//throw new Exception();
	System.out.println("In TRY");
	return "返回值";
}catch(Exception e){
System.out.println("In Catch");

}

finally{
System.out.println("In FINALLY");
return "返回值";
}
				//System.out.println("Afer finally In Return");

}

}

 结果:与测试二一样。

测试(四):

public class Test{
public static void main(String args[]){
System.out.println(a());	
}
private static String a(){
try{
				//throw new Exception();
	System.out.println("In TRY");
	return "返回值";
}catch(Exception e){
System.out.println("In Catch");

}
System.out.println("Afer Catch before finally !");
finally{
System.out.println("In FINALLY");
return "返回值";
}
				//System.out.println("Afer finally In Return");

}

}
 结果:编译报错 finally不带有try。说明try-catch-finally必须连在一起中间不能有语句。

 

结论:try-catch-finally必须连在一起中间不能有语句。return语句只能放到finally块得后面或者是finally块里面的最后一句话。即程序的最后面。即try-(catch)-finally-return的顺序执行。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值