Throwing the (Un)Throwable

Javalobby ate my lunch! I had a more glorious post than this, but they wrote the first part far better, and published sooner. To be fair, accounts of abusing generics to break the java compiler go back as far as generics. To be nitpicky, the inner class didn't work in method #3 because the captured context constitutes an implicit argument. However, I have a key piece of content that will help you actually use unchecked checked exceptions with minimum fuss. Code bomb:
public class Hacks {

@SuppressWarnings("unchecked")
public static <T> T uncheckedCast(Object o) {
return (T) o;
}

private static <T extends Throwable> void uncheckedThrow0(Throwable t)
throws T {
throw Hacks.<T>uncheckedCast(t);
}

public static void uncheckedThrow(Throwable t) {
Hacks.<Error>uncheckedThrow0(t);
}

public static <T extends Throwable> void enableCatch() throws T {}

}

Note that I took the trouble to break the unchecked cast out into it's own method. It's amazingly useful when you want a Class<? extends List<SpecificType>>, but all you have is ArrayList.class or instance.getClass() and you don't want to type the signature yet again. But we're here to see Hacks.enableCatch() let us catch a specific checked exception.

Demo.java:

import java.io.IOException;

public class Demo {

public static void main(String... args) {
IOException t = new IOException();
try {
Hacks.uncheckedThrow(t);
Hacks.<IOException>enableCatch();
throw new AssertionError("Did not throw");
} catch(IOException ioe) {
if(t != ioe)
throw new AssertionError("Threw wrong thing");
}
System.out.println("Success!");
}

}

Now, when you know that deep inside your code you're throwing a specific arcane exception and defeating checked exceptions to do it, you can catch specifically that type.

* I should note that we don't have this checked into our repository.


Close

Add a little SmartBear to your life

Stay on top of your Software game with the latest developer tips, best practices and news, delivered straight to your inbox

By submitting this form, you agree to our
Terms of Use and Privacy Policy

Thanks for Subscribing

Keep an eye on your inbox for more great content.

Continue Reading