What is the best way to get Exception Transparency in Java by using an anonymous inner class to run some code.
The frequent template that I saw in real code uses some Runnable interface to indicate some context for some given code. The best example I can come up with in the JDK is java.security.PrivilegedExceptionAction.
try { boolean success = AccessController.doPrivileged( new PrivilegedExceptionAction<Boolean>() { @Override public Boolean run() throws Exception { // do something // read file FileInputStream fileInputStream = new FileInputStream(new File("someFile")); return true; } } ); } catch (PrivilegedActionException e) { if (e.getCause() instanceof FileNotFoundException) { // handle IO exception } else { // impossible no other checked exception } }
Even while reading the code, you can clearly see that the internal code only throws the file is not found, but we have lost the advantages of the checked exceptions, since the caller does not know which exception is actually selected. A common mistake is to inject code into an anonymous inner class that would throw a new exception, and the code would not force you to handle this exception.
What I want is something like the one below, is this type of behavior achievable without changing the language?
public interface PrivilegedExceptionAction<T,V... extends Throwable> { public T run() throws V; }
source share