是否需要抛出异常而抛出异常? [英] Rethrowing Exception without requiring throws Exception?

查看:83
本文介绍了是否需要抛出异常而抛出异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码:

static void main(String[] args) {
  try {
  } catch (Exception e) {
    throw e;
  }
}

此代码可以编译,而无需在方法签名中添加 throws异常.(它与 Throwable 代替 Exception 的行为类似).

This code compiles without having to add throws Exception to the method signature. (It behaves similarly with Throwable in place of Exception, too).

我理解为什么 可以安全运行,因为实际上 try 块中不会抛出 Exception 不能抛出异常;我想知道在哪里指定了此行为.

I understand why it can be run safely, in that Exception can't actually be thrown in the try block, so a checked exception cannot be thrown; I'm interested to know where this behaviour is specified.

并非仅仅没有达到 throw e :以下代码也可以编译:

It's not simply that the throw e is never reached: the following code also compiles:

static void stillCompilesWithThrownUncheckedException() {
  try {
    throw new NullPointerException();
  } catch (Exception e) {
    throw e;
  }
}

但是,如果抛出一个检查的异常,它不会像我期望的那样编译:

But if you throw a checked exception, it doesn't compile, as I expect:

static void doesNotCompileWithThrownCheckedException() {
  try {
    throw new Exception();
  } catch (Exception e) {
    throw e;  // error: unreported exception Exception; must be caught or declared to be thrown
  }
}

JLS Sec 11.2中.2 ,它说:

一个 throw 语句(第14.18节),其引发的表达式具有静态类型E,并且不是最终或有效的最终异常参数,可以引发E或引发的表达式可以引发的任何异常类.>

A throw statement (§14.18) whose thrown expression has static type E and is not a final or effectively final exception parameter can throw E or any exception class that the thrown expression can throw.

我对此声明的解释是, e 可以引发 Exception ,因为 e 的静态类型是 Exception .然后,在 JLS Sec 11.2.3 :

My interpretation of this statement is that throw e can throw Exception, because the static type of e is Exception. And then, in JLS Sec 11.2.3:

当E是检查的异常类并且E不是方法或构造函数的throws子句中声明的某个类的子类时,如果方法或构造函数主体可以抛出某些异常类E,则是编译时错误./p>

It is a compile-time error if a method or constructor body can throw some exception class E when E is a checked exception class and E is not a subclass of some class declared in the throws clause of the method or constructor.

但这不是前两种情况下的编译时错误.语言规范在哪里描述了这种行为?

But it's not a compile-time error in the first two cases. Where is this behavior described in the language spec?

将其标记为重复,我要问一个后续问题:为什么不 throw e; 在第一个示例中被认为不可达.

having marked it a dupe, I was going to ask the follow-up question: why isn't throw e; considered unreachable in the first example.

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆