Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly ignore exception in Java?

Tags:

java

exception

We all write from time to time code like this:

try {
  // ... some code.
} catch (SomeException e) {
  // ... No action is required, just ignore.
}

Is there any standard code fragment like annotation to show we really intend to ignore exception? Something that shows to other team members and static analyzers we really need to skip this situation like InterruptedException after Thread.sleep()? Something like:

Exception.ignore(e);

Googled around but have not found something standard for such case.

This is especially relevant to tests that assure exceptions:

try {
    action();
    fail("We expected this to fail.");
} catch (ExpectedException e) {
    ignore(e, "OK, so far so good.");
}
like image 613
Roman Nikitchenko Avatar asked Aug 12 '14 13:08

Roman Nikitchenko


2 Answers

The only way to ignore an exception is to catch & swallow it, being very specific on the exception of course, you wouldn't want to catch Exception e, that would be a very bad idea.

try{
  ...  //code
}
catch( VerySpecificException ignore){
   Log(ignore);
}

Logging is obviously optional but a good practice.

like image 195
T McKeown Avatar answered Oct 10 '22 01:10

T McKeown


in order to keep the code up with your exception handling or ignoring, it's nice to name the exception var as ignored:

try {
  action();
} catch (ExpectedException ignored ) {}
like image 24
injecteer Avatar answered Oct 10 '22 03:10

injecteer