豆角茄子子

导航

面试题之异常处理

案例一:

public static void main(String[] args) {
	try {
	    int a = 1;
		try {
		    int b = 1 / 0;
		} catch (Exception e) {
			System.out.println("inner exception..");
			return;
		} finally {
			System.out.println("inner finally..");
		}
	} catch (Exception e) {
		System.out.println("outer exception..");
	} finally {
		System.out.println("outer finally..");
	}
}

运行结果:

inner exception..
inner finally..
outer finally..

解析:

1.异常在catch块中被捕获住,且没有向外抛出,则此异常只能被处理一次;所以不会打印"outer exception..";

2.return只会让程序走出当前所属的花括号范围之外;所以仍会打印"inner finally..";去掉return语句,结果一样。

案例二:

public static void main(String[] args) {
	try {			
	        method1();
	    } catch (Exception e) {
		System.out.println("main exception..");
	    } finally {
		System.out.println("main finally..");
	    }
    }
    public static void method1() {
	try {			
	    method2();
	} catch (Exception e) {
		System.out.println("method1 exception..");
	} finally {
		System.out.println("method1 finally..");
	}
    }
    public static void method2() {
	try {			
		int i = 1 / 0;
	} catch (Exception e) {
		System.out.println("method2 exception..");
	} finally {
		System.out.println("method2 finally..");
	}
}

运行结果:

method2 exception..
method2 finally..
method1 finally..
main finally..

解析:

1.异常在catch块中被捕获住,且没有向外抛出,则此异常只能被处理一次;所以只会在method2中打印"method exception.."。

posted on 2018-11-11 22:32  豆角茄子子  阅读(141)  评论(0编辑  收藏  举报