gpt4 book ai didi

java - 在finally block 中重新抛出异常

转载 作者:行者123 更新时间:2023-12-01 06:13:40 25 4
gpt4 key购买 nike

我写了一个如下的函数,在try block 中我抛出IOException,它由下一个catch block 处理,并再次抛出FileNotFoundException,在finally block 中我再次抛出NULLPointerException。所以我的问题是 FileNotFOoundException 异常是未处理的异常吗?为什么调用函数只得到 NULLPointerException,尽管 FileNotFounException 未处理(我假设)?

static void fun(){
try{
throw new IOException();
}
catch(IOException e){
throw new FileNotFoundException();
}
finally{
throw new NullPointerException();
}
}

最佳答案

您没有正确使用 finally 语句。

根据Java docs:

The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.

所以,是的,你确实有一个未处理的异常。如果您尝试处理多个错误,我会抛出异常,而不是使用像这样的 try/catch :

static void fun() throws FileNotFoundException, NullPointerException{
//your code here

}

然后,当您调用该方法时,您可以将其包含在 try/catch 中:

    try{
YourClass.fun();
}catch(Exception e){
//handle the error.
}finally{
//clean up code, this is optional
}

关于java - 在finally block 中重新抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29324900/

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