对于此示例,正确的重新抛出代码如何?

Chr*_*utz 2 java exception-handling

昨天我在本文中重新介绍了Java 7中新的异常处理.

在文章中,他们展示了一个不能在Java 6中运行的示例(No 4).我只是复制了它.

public class ExampleExceptionRethrowInvalid {

public static void demoRethrow()throws IOException {
    try {

        // forcing an IOException here as an example,
        // normally some code could trigger this.
        throw new IOException("Error");
    }
    catch(Exception exception) {
        /*
         * Do some handling and then rethrow.
         */
        throw exception;
    }
}

public static void main( String[] args )
{
    try {
        demoRethrow();
    }
    catch(IOException exception) {
        System.err.println(exception.getMessage());
    }
}
}
Run Code Online (Sandbox Code Playgroud)

就像在描述的文章中一样,它不会编译,因为类型不匹配 - 抛出IOException-和-throw exception-.在Java 7中它会.所以我的问题是.

如何在Java 6中正确实现这种异常的重新抛出?我不喜欢建议的实现例子没有五.我知道如果未经检查的异常,你尝试处理的是品味和问题.那么我该怎么做才能得到-throws IOException-并保持堆栈跟踪?我应该只将catch更改为IOException并冒险不捕获所有内容吗?

我很好奇你的答案.

NPE*_*NPE 6

简单地抓住IOException,像这样:

public static void demoRethrow()throws IOException {
    try {
        // forcing an IOException here as an example,
        // normally some code could trigger this.
        throw new IOException("Error");
    }
    catch(IOException exception) {
        /*
         * Do some handling and then rethrow.
         */
        throw exception;
    }
}
Run Code Online (Sandbox Code Playgroud)

如果try块内的代码可以抛出除了之外的已检查异常IOException,编译器会将此标记为错误,因此您不会"冒险"没有捕获所有内容.

如果你也对未经检查的异常感兴趣,你也可以捕获并重新抛出RuntimeException(你不需要在throws子句中声明它).