1

I'm wondering how should one handle "contained" exceptions. Because the term isn't concrete enough, let me take an example of PrivilegedActionException.

In short, this exception will in its cause contain any checked exception thrown during the computation within PrivilegedAction.

Now if I have and method computate() throws IOException I'll - if executed on its own - handle it as:

try {
  computate();
} catch (FileNotFoundException ex) {
 // Handle file not found
} catch (SomeOtherSubtypeOfIOException ex) {
 // handle that again
}

Now as this has been executed in PriviledgedAction the only exception I get is PrivilegedActionException:

try {
  Subject.doAs(() -> computate());
} catch (PrivilegedActionException ex) {
  // Now what?
}

I can get the IOException from previous example by calling ex.getCause() but how would that look like? The obvious way looks odd ...

catch (PrivilegedActionException ex) {
  if (ex.getCause() instanceof FileNotFoundException.class) {
    // handle FileNotFound
  } else if (ex.getCause() instanceof xxx) {
    // something else
  }
}
Jan Zyka
  • 17,460
  • 16
  • 70
  • 118
  • This look pretty much the same but better explained: http://stackoverflow.com/questions/10437890/what-is-the-best-way-to-handle-an-executionexception – Jan Zyka May 18 '15 at 09:36

1 Answers1

0

You could get the cause and re-throw it. Then handle exception with an outer try-catch.

catch (PrivilegedActionException ex) {
  Throwable cause = ex.getCause();
  if(cause !=null) throw ex.getCause();
  else ex.printStackTrace();
}
Teddy
  • 4,009
  • 2
  • 33
  • 55