Is it possible to tell the compiler that a method always throws an Exception
java
Solution
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.
Problem
Generally speaking, the Java compiler does not propagate the information that a method "always" throw an Exception, and therefore, does not detect that all code paths are complete. (This is due to the fact that Java compiler compiles each class independently). It's a problem when you want to write something like that. ``` public class ErrorContext { public void fatalISE(String message) { String context = "gather lots of information about the context of the error"; throw new IllegalStateException(context +": " + message); } } public class A { public MyObject myMethod() { if (allIsGood()) { return new MyObject(); } ErrorContext.fatalISE("all is not good"); } } ``` (ie, a kind of "assertion helper" that gathers context information). Because the compiler will complain that myMethod does not always return a MyObject. To my knowledge, there is no specific annotation to indicate that a method always throws.