Java面试题:异常语句的嵌套运用

本文深入探讨Java中异常语句的嵌套使用,通过具体示例解释了try、catch和finally块的执行流程,特别是在方法调用和返回语句中的表现。分析了异常抛出与捕获的机制,以及finally块的执行时机。

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

异常语句的嵌套运用

面试题如下代码,最终输出的结果为?

public class ReturnExceptionDemo {
	public static void methodA() {
		try {
			System.out.println("进入方法A");
			throw new RuntimeException("制造异常");
		} finally {
			System.out.println("用A方法的finally");
		}
	}

	public static int methodB() {
		try {
			System.out.println("进入方法B");
			return 1;
		} catch (Exception e) {
			return 3;
		} finally {
			System.out.println("调用B方法的finally");
		}
	}

	public static void main(String[] args) {
		try {
			methodA();
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
		int i = methodB();
		System.out.println(i);
	}
}

输出的结果为:

进入方法A
用A方法的finally
制造异常
进入方法B
调用B方法的finally
1

代码分析,首先找到主方法

进入try块,执行methodA()

public static void methodA() {
		try {
			System.out.println("进入方法A");
			throw new RuntimeException("制造异常");
		} finally {
			System.out.println("用A方法的finally");
		}
	}

methodA()方法中,首先进入try块,打印“进入方法A”,然后通过throw抛出 RuntimeException(“制造异常”)

随后直接到达finally块,打印"用A方法的finally"

methodA()中的异常并没有处理,异常抛出被主方法(main)中的catch块捕获,执行System.out.println(e.getMessage()); 打印“制造异常”

接下来,执行methodB();

public static int methodB() {
		try {
			System.out.println("进入方法B");
			return 1;
		} catch (Exception e) {
			return 3;
		} finally {
			System.out.println("调用B方法的finally");
		}
	}

进入methodB()中的try块,打印“进入方法B”

return返回1给主方法中的 变量i;

由于methodB()中并没有异常可以捕获,故该方法中的catch块不会执行,

跳转到finally块,打印 "调用B方法的finally"

最后,主方法中执行System.out.println(i); i=1,打印“1”

需要注意的是,如果methodB()中能够捕获到潜在的异常,是可以执行catch语句的,但是,return 1和异常抛出只能执行其中一句。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值