添加 return 最后隐藏异常
Adding return in finally hides the exception
我有以下代码
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!
}
}
谁能解释一下这是怎么回事?为什么错误消失了?
注意:我写这段代码纯粹是为了实验目的!
错误消失,因为您的代码现在有效。 (不好,但有效。)
如果一个 finally
块只有一个直接的 return;
语句,那么整个 try/catch/finally 或 try/finally 语句不会抛出任何异常 - 所以你不会不需要声明它可以抛出异常。
在您的原始代码中,您的 try
块可能(嗯,它 将 )抛出 Exception
(或 CustomException
显然是代码)- 这是一个已检查的异常,这意味着您必须捕获它或声明该方法可能会抛出它。
根据 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.
所以您的代码现在可以正常执行了。
我有以下代码
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!
}
}
谁能解释一下这是怎么回事?为什么错误消失了?
注意:我写这段代码纯粹是为了实验目的!
错误消失,因为您的代码现在有效。 (不好,但有效。)
如果一个 finally
块只有一个直接的 return;
语句,那么整个 try/catch/finally 或 try/finally 语句不会抛出任何异常 - 所以你不会不需要声明它可以抛出异常。
在您的原始代码中,您的 try
块可能(嗯,它 将 )抛出 Exception
(或 CustomException
显然是代码)- 这是一个已检查的异常,这意味着您必须捕获它或声明该方法可能会抛出它。
根据 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.
所以您的代码现在可以正常执行了。