Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare-and-throw vs. throw-without-being-declared exceptions

Tags:

java

exception

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?

like image 267
Martin08 Avatar asked Nov 21 '08 18:11

Martin08


People also ask

Is it possible to throw exception without using throws exception in Java?

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.

What is the difference between throw and throws in Java exception handling?

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.

What happens if you invoke a method and it throws a checked exception that it does not catch?

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.

Why do methods have to declare the exceptions they can throw?

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.


1 Answers

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.

like image 118
Dave DiFranco Avatar answered Oct 02 '22 19:10

Dave DiFranco