gpt4 book ai didi

java - 为什么 catch block 是可选的?

转载 作者:行者123 更新时间:2023-12-02 11:23:49 25 4
gpt4 key购买 nike

我有以下代码

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

}
}

这给出了错误

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

我的问题是,为什么catch block 被设计为可选的,而没有办法避免没有catch?

<小时/>

从finally()的角度来看,我明白

finally 应该至少有一个 try block ,catch 是可选的。 finally block 的目的是确保无论是否抛出异常,内容都会得到清理。根据JLS

A finally clause ensures that the finally block is executed after the try block and any catch block that might be executed, no matter how control leaves the try block or catch block.

<小时/>

编辑:

通过在f​​inally block 中添加return,编译器不会给出错误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
}
}

最佳答案

My Question is why was it designed that the catch block is optional, when there is no way of getting around not having a catch?

是的,有:声明该方法抛出异常:

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

}
}
不带 catch

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

这是一个可以使用的示例( live copy ):

private static class CustomException extends Exception {
}
public static void main (String[] args) throws java.lang.Exception
{
try
{
System.out.println("Calling nocatch(false)");
nocatch(false);
}
catch (CustomException ce) {
System.out.println("Caught CustomException for false case");
}
try
{
System.out.println("Calling nocatch(true)");
nocatch(true);
}
catch (CustomException ce) {
System.out.println("Caught CustomException for true case");
}
}

public static void nocatch(boolean foo) throws CustomException
{
try
{
if (foo) {
System.out.println("Throwing");
throw new CustomException();
}
}
finally
{
System.out.println("In finally");
}
System.out.println("Reached outside the try/finally block");
}

输出:

Calling nocatch(false)In finallyReached outside the try/finally blockCalling nocatch(true)ThrowingIn finallyCaught CustomException for true case

As you can see, the finally block's code runs regardless of whether an exception occurred, but the code after the try/finally doesn't.


Re your follow-up asking why adding return within the finally makes the error go away:

try
{
throw new CustomException();
}
finally
{
return; // <=== Makes the compiler happy (but don't do it!)
}

有趣的边缘情况!这是因为 finally block 中的代码始终运行,因此您将始终返回而不是抛出,从而隐藏发生的异常。例如,这是序列:

  1. throw new CustomException() 抛出异常,将控制权转移到 finally block

  2. finally block 中的代码从方法中发出正常返回

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

关于java - 为什么 catch block 是可选的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28856947/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com