【发布时间】:2015-05-05 14:07:18
【问题描述】:
我有以下代码
public static void nocatch()
{
try
{
throw new Exception();
}
finally
{
}
}
这给出了错误
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Unhandled exception type CustomException
我的问题是,当没有 catch 无法绕过时,为什么将 catch 块设计为可选?
从 finally() 的角度来看,我理解
finally 应该至少有一个 try 块,catch 是可选的。 finally 块的目的是确保无论是否引发异常,都可以清理内容。根据JLS
finally 子句确保 finally 块在 try 块和任何可能执行的 catch 块之后执行,无论控制如何离开 try 块或 catch 块。
编辑:
通过在 finally 块中添加返回,编译器不会给出错误 WHY?!
public static void nocatch()
{
try
{
throw new Exception();
}
finally
{
return; //By adding this statement, the compiler error goes away! Please let me know why
}
}
【问题讨论】:
-
关于“为什么”的问题几乎是基于意见的;事实上,Java 是(据我所知)唯一具有检查异常概念的语言,而且您的
CustomException似乎就是这样一个异常。并且有处理已检查异常的规则。 -
它允许您实现
finally子句。它不会“隐藏”异常。 -
将在此处尝试使用资源 (docs.oracle.com/javase/tutorial/essential/exceptions/…) 以省略 finally ;)
-
CustomException是什么无关紧要。为了争论,我们只考虑Exception -
@HotLicks:“责备”当然是指“对 Java 语言和环境的一项突出特性给予应有的尊重和尊重”。 ;-)
标签: java exception exception-handling try-catch try-catch-finally