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;
}
There is no way to do that with a throws . The syntax of anonymous does not allow you to put a throws clause on the (implicit) constructor. The (implicit) constructor implicitly throws all of the superclass constructor you are using.
Anonymous classes are inner classes with no name. Since they have no name, we can't use them in order to create instances of anonymous classes. As a result, we have to declare and instantiate anonymous classes in a single expression at the point of use. We may either extend an existing class or implement an interface.
A checked exception must be handled either by re-throwing or with a try catch block, whereas an unchecked isn't required to be handled. A runtime exception is a programming error and is fatal whereas a checked exception is an exception condition within your code's logic and can be recovered or re-tried from.
If a method which is used within a Java 8 stream processing throws a checked exception, this exception has to be handled. One way to do this is to wrap the checked exception with a java. lang. RuntimeException and throw it.
I don't see why not. The following code worked.
interface RunIt < E extends Exception >
{
void run ( ) throws E ;
}
class App
{
public static void main ( String [ ] args )
{
RunIt < RuntimeException > r = new RunIt < RuntimeException > ( )
{
public void run ( )
{
throw new RuntimeException ( ) ;
}
} ;
r . run ( ) ;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With