如何存储异常

时间:2017-08-03 14:15:04

标签: java if-statement exception

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

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

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

logError(String description, Throwable error);

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

6 个答案:

答案 0 :(得分:6)

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

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

正如您可以在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)
}

答案 1 :(得分:2)

例外不会像这样工作。一旦throw出现异常,代码就会被中断,并且不再运行。您可以在下一个try-catch块中访问抛出的异常,如下所示:

try{
    //code that may throws an exception like this:
    throw new Exception();
}catch(Exception e){
    eventLogger.logError("Your message", e);
}

如果你想在之前记录之前的异常,你必须首先创建它,然后记录它并最终抛出它。

Exception e = new Exception();
eventLogger.logError("your message", e);
throw e;

答案 2 :(得分:1)

在您的示例中永远不会到达记录器,因为Exception之前会抛出一行。要记录错误,请在catch块的try - catch部分执行此操作

try {
    throw new Exception();
} catch (Exception e) {
   eventLogger.logError("The count is not zero",e);
} 

答案 3 :(得分:0)

当您抛出错误时,您将终止该方法的执行。这使你的第二个声明无法访问。

在方法标题中,声明methodName() throws Exception。现在,无论何处调用此方法,您都知道存在可能引发异常的风险。

try{
    methodName();
}
catch(Exception e){
    eventLogger.log(e);
}

切换订单对您没有帮助,因为e未被理解。

答案 4 :(得分:0)

异常是可抛出的,一旦throw new Exception();被执行,那么

eventLogger.logError("The count is not zero",e) 

以上陈述将无法到达。因此,您需要在抛出异常之前完成所有操作(如方法调用等)。您应该在catch子句中编写异常打印代码。

所以最后你需要改变代码如下......

try{
    if(count !=0) {
     // do method callings
      throw new Exception();
   }else{
    // write alternative flow here
   }
}
catch(Exception exception){
  logger.error(exception);
  eventLogger.logError("The count is not zero",exception);
}

答案 5 :(得分:0)

如果您正在做的事情将抛出异常(例如调用File.open()或其他东西),请将其包装在try-catch-finally

bool errorOccurred = false;
try {
    // do things that can cause errors here.    
} catch (Exception e) {
    // things in here happen immediately after an exception in try-block
    eventLogger.logError("The count is not zero", e);
    errorOccurred = true;
} finally {
    // always happens after a try, regaurdless or exception thrown or not
    if (errorOccurred) { 
        /* report error to user or something else */ 
    } else {
        /* finish up */
    }
}

但如果您只想记录满足特定条件,则可以创建自己的异常对象,并将其传递给错误记录方法,而不使用try catch

if (count != 0) {
    Exception ex = new Exception(); 
    // set the properties you need set on ex here 
    errorLogger.logError("The count is not zero", ex);
} else {
    // do something else
}

对于第二个选项,您可以使用继承自Exception的不同子类,或者您甚至可以自己实现。