gpt4 book ai didi

java - 如何存储异常

转载 作者:搜寻专家 更新时间:2023-11-01 01:31:46 25 4
gpt4 key购买 nike

我想抛出异常并显示它。在我的 IF block 中,我抛出了异常。我是否必须存储异常以将其作为变量传递到前面的方法中。

if(count !=0) {
throw new Exception();
eventLogger.logError("The count is not zero",e)
}
else{
// do something else
}

记录器将 Throwable error 作为参数。

logError(String description, Throwable error);

如何将我抛出的异常传递给这个方法

最佳答案

一旦抛出异常,您的程序就会停止运行。因此,您必须更改语句的顺序。

if(count !=0) {
Exception e = new Exception();
eventLogger.logError("The count is not zero",e)
throw e;
}
else{
// do something else
}

正如您在 Java API 中所读到的那样类异常扩展可抛出

编辑

正如 Zabuza 提到的,可以在 try-catch block 中处理异常。这将是一种更优雅的方式:

try{
if(count !=0) {
throw new Exception();
}else{
// do something else
}
}
catch(Exception e){
eventLogger.logError("The count is not zero",e)
}

关于java - 如何存储异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45486808/

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