I want to write a custom Throwable that is unchecked.
There are ways to trick the compiler at throw time (e.g. Utility class that re-throws a throwable as unchecked?), which I have implemented thus:
public class CustomThrowable extends Throwable {
public CustomThrowable(String message) {
super(message);
}
@SuppressWarnings("unchecked")
public <T extends Throwable> T unchecked() throws T {
throw (T) this;
}
}
but I'm running into issues at "catch time":
try {
throw new CustomThrowable("foo").unchecked();
}
catch (CustomThrowable t) { } // <- compiler error because the try block does not "throw" a CustomThrowable
Is there a way to simply implement an unchecked Throwable, or is RuntimeException the only way to do that? I had wanted to avoid inheriting from RuntimeException because my throwable is not an exception, but instead a yield instruction.
Update:
Another reason to avoid extending RuntimeException is that my CustomThrowable will get caught by generic catch (Exception ex) { } blocks. Thus, if I want to communicate information from within the stack, each layer needs to potentially be aware that CustomThrowable might come through and explicitly catch-rethrow it; this awareness is a large part of what one is trying to avoid when using the Throwable design.
Per Why runtime exception is unchecked exception? (and the unquestionable authority of Jon Skeet ;), it appears that unchecked-exception support is built into the java compiler, and is probably not something I can plug into.
Quoting from Jon's post:
I'm still hoping that someone else will come up with a "yes you can" answer, so I'll wait a few more days before closing this question.