【问题标题】:Throwing an exception within a catch block在 catch 块中抛出异常
【发布时间】:2016-10-14 17:53:13
【问题描述】:

我试图捕获一个特定的异常并处理它,然后抛出一个通用异常,该异常执行代码来处理任何异常。这是如何实现的?这个 sn-p 没有捕捉到 Exception 所以输出是

Exception in thread "main" java.lang.Exception
    at Main.main(Main.java:10)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
IOException specific handling

Process finished with exit code 1

sn-p:

import java.io.IOException;

public class Main {

    public static void main(String[] args) throws Exception {
      try {
        throw new IOException();
      } catch (IOException re) {
        System.out.println("IOException specific handling");
        throw new Exception();
      } catch (Exception e) {
        System.out.println("Generic handling for IOException and all other exceptions");
      }
    }
}

【问题讨论】:

  • 这在什么方面失败了?您到达了catch 块,因为消息"IOException specific handling" 已打印。然后应用程序以异常退出,因为您抛出了异常
  • @David 我希望执行 Exception 块中的代码。
  • @newToScala 在第一条评论中查看我的链接问题,它解释了为什么/如何您的代码完全按照它应该的方式执行。
  • @newToScala:IOException 块优先,因为抛出了 IOException。只使用了一个catch 块。如果你想捕捉你正在抛出的Exception,你需要将整个操作包装在一个 try/catch 中。

标签: java


【解决方案1】:

你在 IOException 的 catch-block 中抛出的异常永远不会被捕获。这就是为什么你必须在你的 main 方法中添加“抛出异常”。

在同一次尝试之后,多个 catch-block 的行为类似于 if..else 级联,以便寻找适合处理特定异常的 catch-block。

将整个 try..catch 嵌入到另一个 try..catch 块中:

try {
  try {
    throw new IOException();
  } catch (IOException re) {
    System.out.println("IOException specific handling");
    throw new Exception();
  }
} catch (Exception e) {
    System.out.println("Generic handling for IOException and all other xceptions");
  }

通常将原始异常嵌入到新的通用异常中,这样您就不会在最终异常处理时丢失信息(例如,如果您想记录堆栈跟踪以识别异常发生的确切位置):

    throw new Exception(re);

在最后的 catch-block 中:

    e.printStackTrace();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-18
    • 1970-01-01
    • 2012-09-21
    • 2012-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多