Java 为什么catch块是可选的?

Java 为什么catch块是可选的?,java,exception,exception-handling,try-catch,try-catch-finally,Java,Exception,Exception Handling,Try Catch,Try Catch Finally,我有以下代码 public static void nocatch() { try { throw new Exception(); } finally { } } 这就产生了错误 Exception in thread "main" java.lang.Error: Unresolved compilation problem: Unhandled exception type CustomException 我的问题是,

我有以下代码

public static void nocatch()
{
    try
    {
        throw new Exception();
    }
    finally
    {

    }
}
这就产生了错误

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
Unhandled exception type CustomException
我的问题是,当无法绕过没有捕捉的情况时,为什么设计捕捉块是可选的


从我的角度来看,我理解这一点

最后
应该至少有一个
try
块,
catch
是可选的。finally blocks的目的是确保无论是否抛出异常,都能清理这些内容。按照

finally子句确保finally块在try块和可能执行的任何catch块之后执行,无论控件如何离开try块或catch块


编辑:

通过在finally块中添加一个return,编译器不会给出错误原因

public static void nocatch()
{
    try
    {
        throw new Exception();
    }
    finally
    {
        return; //By adding this statement, the compiler error goes away! Please let me know why
    }
}
我的问题是,当无法绕过没有捕捉的情况时,为什么设计捕捉块是可选的

是存在:声明该方法引发异常:

public static void nocatch() throws CustomException
{
    try
    {
        throw new CustomException();
    }
    finally
    {

    }
}
try/finally
without
catch
是为了确保您清理任何需要清理的内容,即使您自己没有处理异常。(请确保不允许从
finally
中引发任何其他异常,否则将隐藏主异常。)

下面是一个可以使用()的示例:

输出:

Calling nocatch(false) In finally Reached outside the try/finally block Calling nocatch(true) Throwing In finally Caught CustomException for true case 有趣的边缘案例!这是因为
finally
中的代码始终运行,因此您将始终返回而不是抛出,从而隐藏发生的异常。例如,这是顺序:

  • throw new CustomException()
    抛出异常,将控制权最终转移到

  • 最后块中的代码从方法发出正常返回


  • 这隐藏了异常发生的事实;实际上,您已经通过
    finally
    块“处理”了异常(而没有实际处理它)。总的来说,这不是一个好主意;使用
    catch
    处理异常,或者在方法上声明它们,以便调用代码可以处理它们。

    关于“为什么”的问题基本上是基于观点的;事实上,Java是(据我所知)唯一具有检查异常概念的语言,而且您的
    CustomException
    似乎就是这样一种异常。还有处理选中异常的规则。它允许您实现
    finally
    子句。它不会“隐藏”异常。将在此处抛出try with resources(),以便最终省略;)无论什么是
    自定义异常
    。为了论证,我们只考虑代码>异常< /代码> @热舔:当然,“责备”,你的意思是“给予应有的信任和尊敬,java语言和环境中的一个突出特点。”如果您有一个throws子句,那么首先就不需要try{}。但是如果我理解正确,在上面的例子中,我们添加try块只是为了得到finally。。。是吗?@codeMan:是的:目的是说“我要做这件事,这可能会引发异常;不管是否发生异常,一定要运行我的
    最终
    代码,这样我以后才能清理。”这就是为什么标准
    try
    后面必须跟着
    catch
    最终
    (或两者兼而有之)的原因(try with resources可以完全独立,因为它有隐式的
    catch
    finally
    子句)。谢谢你提供的额外信息。还有一件事我无法理解。我已经编辑了我的问题,请你看一看。@codeMan:在底部添加了一点:因为如果你这样做,你的方法将不再抛出任何错误。 Calling nocatch(false) In finally Reached outside the try/finally block Calling nocatch(true) Throwing In finally Caught CustomException for true case
    try
    {
        throw new CustomException();
    }
    finally
    {
        return; // <=== Makes the compiler happy (but don't do it!)
    }