最后添加return会隐藏异常

cod*_*Man 7 java exception-handling exception try-catch try-catch-finally

我有以下代码

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

    }
}
Run Code Online (Sandbox Code Playgroud)

这给出了错误

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
Unhandled exception type CustomException
Run Code Online (Sandbox Code Playgroud)

这是预期的,但returnfinally块中添加语句会使错误消失

public static void nocatch()
{
    try
    {
        throw new Exception();
    }
    finally
    {
        return; //makes the error go away! 
    }
}
Run Code Online (Sandbox Code Playgroud)

有人可以解释一下发生了什么事吗?为什么错误会消失?

注意:我编写此代码纯粹是为了实验目的!

Jon*_*eet 7

错误消失,因为您的代码现在有效.(不好,但有效.)

如果一个finally块只有一个直接return;语句,那么整个try/catch/finally或try/finally语句不能抛出任何异常 - 所以你不需要声明它可以抛出异常.

在你的原始代码中,你的try块可以(好吧,它)抛出Exception(或者CustomException显然是你的真实代码) - 这是一个经过检查的异常,这意味着你必须捕获它或声明方法可能抛出它.