V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
Newyorkcity
V2EX  ›  问与答

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

  •  
  •   Newyorkcity · 2018-03-23 18:15:20 +08:00 · 2153 次点击
    这是一个创建于 2439 天前的主题,其中的信息可能已经有所发展或是发生改变。
    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 一个新的异常就必须如此定义呢...
    谢谢

    1 条回复    2018-03-24 08:23:58 +08:00
    lzdhlsc
        1
    lzdhlsc  
       2018-03-24 08:23:58 +08:00   ❤️ 1
    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 机制没有生效。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   5416 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 23ms · UTC 06:52 · PVG 14:52 · LAX 22:52 · JFK 01:52
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.