In Java, what is the difference between the twin methods?
public void methodA() throws AnException {
//do something
throw new AnException();
}
public void methodA() {
//do the same thing
throw new AnException();
}
I have a intuition that it has something to do with being a well-designed method (because I put methodA in an interface, declared it the way methodA* does in its implementation and received a warning from Java that "A* cannot override A because A* doesn't throw AnException").
Is this speculation correct?
Is there any other subtle connotations in the two ways of doing things?
Without using throwsWhen an exception is cached in a catch block, you can re-throw it using the throw keyword (which is used to throw the exception objects). If you re-throw the exception, just like in the case of throws clause this exception now, will be generated at in the method that calls the current one.
Both throw and throws are concepts of exception handling in Java. The throws keyword is used to declare which exceptions can be thrown from a method, while the throw keyword is used to explicitly throw an exception within a method or block of code.
you get a compile error. Specifically for your question, if you invoke a method that is declared to throw Exception(s) you must either try/catch the method invocation, or declare that your method throws the exceptions. The problem was that I didn't know that there were checked and unchecked exceptions.
If the programmer did not declare that the method (might) throw an exception (or if Java did not have the ability to declare it), the compiler could not know and it would be up to the future user of the method to know about, catch and handle any exceptions the method might throw.
If AnException is a checked exception (in other words, if it doesn't extend RuntimeException) then methodA won't compile. Checked exceptions must always be declated.
If AnException is an unchecked exception (if it does extend RuntimeException), then either is allowed by the java compiler, and either is interpreted equivalently by the java runtime. methodA is still probably still preferred in this case, for the reasons of documentation. The javadoc for your method will show that it might throw AnException. It's good to let users of your method know what Exceptions they should expect.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With