将 catch(Exception ex)中的 ex 抛出去可以不在方法上声明,但在 catch(){}中 throw 一个 new Exception()就必须在方法上声明,这是为什么?

2018-03-23 18:15:20 +08:00
 Newyorkcity
public class TestException {  
    public static void main(String args[]) {
    	TestException test = new TestException();
    	try {
    		test.testA();
    	}catch(Exception e) {
    		System.out.println("A has been got");
    	}
    	
    	try {
    		test.testB();
    	}catch(Exception ex) {
    		System.out.println("B has been got");
    	}
    } 
    public void testA() {
    	try {
	    	int a = 1;
	    	int b = 0;
	    	int c = a/b;
    	}catch(Exception ex) {
    		System.out.println("interesting.");
    		throw ex;
    	}finally {
    		System.out.println("in B,I am sure that I can work.");
    	}
    }
    public void testB(){ //这一行如果不改成 public void testB() throws Exception 则编译必然不通过
    	try {
    		int a=1;
    		int b=0;
    		int c = a/b;
    	}catch(Exception e) {
    		throw new Exception();
    	}
    }
}

不管怎么说两个方法都存在抛出行为,为何 New 一个新的异常就必须如此定义呢...
谢谢

2107 次点击
所在节点    问与答
1 条回复
lzdhlsc
2018-03-24 08:23:58 +08:00
https://docs.oracle.com/javase/8/docs/technotes/guides/language/catch-multiple.html#rethrow

In detail, in Java SE 7 and later, when you declare one or more exception types in a catch clause, and rethrow the exception handled by this catch block, the compiler verifies that the type of the rethrown exception meets the following conditions:

The try block is able to throw it.
There are no other preceding catch blocks that can handle it.
It is a subtype or supertype of one of the catch clause's exception parameters.

我的猜测是在 testB 中的 new Exception() 不是 try block throw 出来的, 所以上述 rethrow 机制没有生效。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/440863

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX