有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在中添加return最终隐藏了异常

我有以下代码

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

    }
}

这就产生了错误

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
Unhandled exception type CustomException

这与预期的一样,但是在finally块中添加return语句会使错误消失

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

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

注意:我写这段代码纯粹是为了实验目的


共 (1) 个答案

  1. # 1 楼答案

    根据javadoc

    The finally block always executes when the try block exits. 
    This ensures that the finally block is executed even if an unexpected exception occurs.
    

    所以你的代码现在做得很正确