关于在Java中重新抛出异常,我有一个非常简单的问题.
这是代码片段:
public static void main(String[] args) throws FileNotFoundException {
try {
FileReader reader = new FileReader("java.pdf");
} catch (FileNotFoundException ex) {
throw ex;
}
}
public static void main(String[] args) throws FileNotFoundException {
FileReader reader = new FileReader("java.pdf");
}
为什么我们需要在第一个版本中重新抛出ex而第二个版本看起来更优雅?什么可能是好处,哪个版本比另一个更受欢迎?
解决方法:
你是对的.第二个版本更好.而且第一个版本没有任何意义.除了异常的堆栈跟踪将是“错误的”之外,它也是如此.
“重新抛出”异常有以下原因:
>如果你以前有事情要做.
>如果捕获一种类型的异常并抛出其他类型的异常:
例:
try {
// do something
} catch (IOException ioe) {
throw new IllegalStateException(ioe);
}
标签:java,exception,exception-handling
来源: https://codeday.me/bug/20190927/1823154.html