如何存储异常

lea*_*ser 4 java if-statement exception

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

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

记录器具有Throwable错误作为参数.

logError(String description, Throwable error);
Run Code Online (Sandbox Code Playgroud)

如何将抛出的异常传递给此方法

osa*_*ger 6

抛出异常后,程序将停止运行.因此,您必须更改语句的顺序.

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

正如您可以在Java API中阅读的那样,Exception类扩展了Throwable

编辑

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

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