Is it possible to tell the compiler that a method always throws an Exception

A simple workaround is to let your fatalISE method not throw the exception, but only create it:

public class ErrorContext {
    public IllegalStateException fatalISE(String message) {
        String context = "gather lots of information about the context of the error";
        return new IllegalStateException(context +": " + message);
    }
}

public class A {
    public MyObject myMethod() {
        if (allIsGood()) {
            return new MyObject();
        }
        throw ErrorContext.fatalISE("all is not good");
    }
}

This way the compiler will know not to complain about a missing return. And forgetting to use the throw is unlikely, exactly because the compiler will usually complain.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)