Let's say you have some method declaring throwing an unchecked exception
EDIT: let's say it's not you who designed this method, but authors of a very respectable framework (Spring, aekhm!), you're just calling it
void someMethod() throws UncheckedException;
My first question is:
Let's say you have another method that's calling someMethod
void someOtherMethod() {
someMethod()
}
My second question is:
UncheckedException
in the someOtherMethod
?Just a little background:
Spring framework's exception are based on unchecked exceptions. So for example some methods are throwing (and declaring it in the throws
) DataAccessException. If my code is using these calls, should it or should it not declare throwing these exceptions? And why?
There is no need to declare unchecked exceptions in the throws ...
clause of a method. As stated in the Java Language Specification, "It is permitted but not required to mention unchecked exception classes in a throws clause".
It is common practice to list unchecked exceptions in your Javadoc if you anticipate that users of your API might encounter them. A common example of this is to list why an IllegalArgumentException
might be thrown.
If you wrap one method with another, apply the Effective Java principle of throwing exceptions suitable to the level of abstraction (Item 61). This should be applied to both checked exceptions and expected unchecked exceptions.
I recommend reading chapter 9 in the great book "Effective Java". You will get all the answers to your questions and you will enjoy a great reading.
Specifically for you questions:
Use the Javadoc @throws tag to document each unchecked exception that a method can throw, but do not use the throws keyword to include unchecked exceptions in the method declaration
Best practice is to not declare unchecked exceptions at all. You don't see methods like this:
public void foo() throws NullPointerException {...}
You should only use throws for Checked Exceptions
. By saying throws
you expect clinet to handle his Exception in any way and this is not true for Unchecked Exceptions
EDIT:
There has been some lively discussion in comments so just to clarify: you don't have to declare Unchecked Exceptions
which doesn't mean you cannot, although in most cases you shouldn't. I prefer to mention them in javadoc style comments rather than in throws
clause. There is plenty other examples where you generally shouldn't do something but in some cases you may need to. In my opinion the bottom line is: no, you shouldn't be listing Unchecked Exceptions
in throws clause
.
To my mind, best practice is to not use throws in the head of the method for unchecked exception, but don't forget to document every exception (checked or not) thrown by your method :
/**
* Some doc
* @throws IllegalArgumentException if ...
*/
public void m() {
//...
throw new IllegalArgumentException();
}
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