What is the best practice way of getting Exception Transparency in Java when using an anonymous inner class to run some code.
A frequent pattern that I have seen in real code is using some pseudo Runnable type interface to specify some context for some given code. The best example I can think of in the JDK is the 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 though reading the code you can clearly see the inner code only throws a File not found, but we lost the benefits of checked exceptions as the caller is unaware of what exception is actually thrown. A Common bug would be to introduce code into the anonymous inner class that would thrown a new exception and the code would not force you to handle that exception.
What I want is something like what’s below, is this type of behaviour achievable without a language change?
public interface PrivilegedExceptionAction<T,V... extends Throwable>
{
public T run() throws V;
}
I don’t see why not. The following code worked.