How to write an unchecked Throwable in java

Gordon Bean :

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.

Gordon Bean :

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:

It's explicitly in the specification, section 11.1.1:

RuntimeException and all its subclasses are, collectively, the runtime exception classes.

The unchecked exception classes are the runtime exception classes and the error classes.

The checked exception classes are all exception classes other than the unchecked exception classes. That is, the checked exception classes are all subclasses of Throwable other than RuntimeException and its subclasses and Error and its subclasses.

So yes, the compiler definitely knows about RuntimeException.

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=164408&siteId=1