Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
229 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...