Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store an exception

I want to throw an exception and to display it. In my IF block I throw the exception. Do I have to store the exception to pass it as a variable in the method which precedes.

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

The logger has Throwable error as a parameter.

logError(String description, Throwable error);

How can I pass the exception I thrown to this method

like image 614
learningUser Avatar asked Jan 03 '23 15:01

learningUser


1 Answers

Once the Exception is thrown, your program stops running. Thus you have to change the order of your statements.

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

As you can read in the Java API the class Exception extends Throwable

EDIT

As Zabuza mentioned, it's possible to handle the exception in a try- catch block. This would be a more elegant way:

try{
    if(count !=0) {
      throw new Exception();
   }else{
    // do something else
   }
}
catch(Exception e){
  eventLogger.logError("The count is not zero",e)
}
like image 141
osanger Avatar answered Jan 13 '23 15:01

osanger