Java SE 6(和更早版本)的更精确的重新抛出异常 [英] More precise re-throw exception with Java SE 6 (and prior versions)

查看:122
本文介绍了Java SE 6(和更早版本)的更精确的重新抛出异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下程序:

class FirstException extends Exception {}

class SecondException extends Exception {}

class RethrowException {
     public void rethrowMethod() throws FirstException, SecondException {
          boolean flag = true;
          try {
              if(flag)
                  throw new FirstException();
              else
                  throw new SecondException(); 
          }
          catch(Exception ex) {
              throw ex;   // does not compile "Unhandled exception type Exception" 
          }
     }
}

此错误仅发生在Java SE 6(或更早版本)中,因为首先,当我们构建 catch块(catch(Exception ex))时,由ex指定的异常对象的类型为 FirstException (或SecondException)。但是,当 ex 被重新抛出( throw ex )时,Java编译器执行以下3个任务:

This error just happens with Java SE 6 (or prior versions) because firstly, when we build the "catch" block (catch(Exception ex)), the exception object, specified by ex, has the type of FirstException (or SecondException). But, when ex is re-thrown (throw ex), the Java compiler performs 3 tasks as follows:


  1. 将 ex释放到系统。

  2. 初始化类型为新的异常对象 ex的异常

  3. 抛出 ex-这是Exception的实例,而不是 FirstException (或 SecondException

  1. Release "ex" to system.
  2. Initialization new exception object, "ex" that has the type of Exception
  3. Throw "ex" - that is instance of Exception, right now, not instance of FirstException (or SecondException)

因此,在Java SE 6中,我们不能使用更精确地重新抛出异常 ,原因如下。但是,在Java SE 7(或更高版本)中,我们可以这样做,因为当我们重新抛出 ex 时,运行时系统不会释放并初始化新的对象 ex 。它将检查(查找) ex1的来源(上面的try块),因此知道 ex FirstException SecondException`。

Thus, in the Java SE 6, we cannot use "more precisely rethrow exception" because the reason following. However, in the Java SE 7 (or later), we can do that, because when we re-throw ex, the runtime system does not release and initialize new object ex. It will check (find) where ex1 come from (the try block above), and so know thatexis an instance ofFirstExceptionorSecondException`.

我上面的解释正确与否?

My explanation above is correct or not?

推荐答案

通过捕获异常并将其从 catch 块中抛出,不会创建新的异常实例,

No new exception instance is created by catching the exception and throwing it from the catch block, in any version on Java.

在Java 6-中,捕获的异常的 type 被声明为 Exception 放在 catch 块中,因此这就是编译器认为正在抛出的内容。

In Java 6-, the type of the caught exception is declared as Exception by the catch block, so that is what the compiler thinks is being thrown.

在更高的版本中,推断异常的类型仅限于从 try 块抛出的可以

In later versions, the type of the exception was inferred to be bounded to only what could be thrown from the try block.

这篇关于Java SE 6(和更早版本)的更精确的重新抛出异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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