Java – declare and throw and throw without is declared exceptions

What is the difference between dual methods in Java?

public void methodA() throws AnException {
    //do something
    throw new AnException();
}

public void methodA() {
    //do the same thing
    throw new AnException();
}

I have an intuition that it is related to a well-designed method (because I put methoda in an interface, it is declared as the way methoda * is implemented, and I receive a warning from Java, "a * cannot override a because a * does not throw an exception")

Is this guess correct?

Do the two ways of doing things have other subtle connotations?

Solution

If anexception is a checked exception (in other words, if it does not extend runtimeException), methoda will not be compiled Exceptions checked must always be rejected

If anexception is an unchecked exception (if runtimeException is extended), it can be allowed by the java compiler or interpreted equivalently by the Java runtime In this case, method a may still be preferred for documentation reasons Your method's Javadoc will show that it may throw anexception It's good to let the users of your method know what exceptions they should expect

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>