How to save an exception

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

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

The logger has a Throwable error value as a parameter.

logError(String description, Throwable error);

How to pass the exception that I selected for this method

+4
source share
6 answers

As soon as the exception is thrown, your program will stop working. Therefore, you must reorder 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 Exception class extends Throwable.

EDIT

, try-catch. :

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

. 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

, Exception . , catch try - catch

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

. .

methodName() throws Exception. , , , , .

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

, e .

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);
}
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
}

For the second option, you can use different subclasses of inheritance from Exception, or you can even make your own implementation.

0
source

Source: https://habr.com/ru/post/1682950/


All Articles