Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should unchecked Exception be described in JavaDoc?

Tags:

java

javadoc

I have the following code:

public User getUserById(Long id) {
checkUserExists(id);
return repo.findOne(id);
}

private void checkUserExists(Long id) {
    if (id == null || !repo.exists(id)) {
        throw new NoUserFoundException("No User exists with id: " +id);
    }
}

According to Oracle:

"Unchecked exceptions do not need to be declared in a method or constructor's throws clause if they can be thrown by the execution of the method or constructor and propagate outside the method or constructor boundary."

Do I have to describe the exception anyway in the JavaDoc (Without the @throws clause, but only describe?) What is the best way to describe such an unchecked exception in JavaDoc?

like image 932
trap Avatar asked May 23 '18 08:05

trap


People also ask

Should unchecked exceptions be documented?

In general, you shouldn't document al the exceptions that can arise. You can't predict them all, and you're very likely to forget one. So, document the obvious ones, the one you though of. Try to list the most exceptions as possible, but don't spend to much time on it.

Should we handle unchecked exceptions in Java?

An unchecked exception (also known as an runtime exception) in Java is something that has gone wrong with the program and is unrecoverable. Just because this is not a compile time exception, meaning you do not need to handle it, that does not mean you don't need to be concerned about it.

Is it good practice to throw RuntimeException?

Generally speaking, do not throw a RuntimeException or create a subclass of RuntimeException simply because you don't want to be bothered with specifying the exceptions your methods can throw.

Is IllegalArgumentException checked or unchecked?

IllegalArgumentException is an unchecked Java exception (a.k.a. runtime exception). It derives from RuntimeException , which is the base class for all unchecked exceptions in Java. Because IllegalArgumentException is an unchecked exception, the Java compiler doesn't force you to catch it.


1 Answers

You are writing Javadoc for the user of your method. If it's useful for that user to know that it may throw an exception, document it!

In your case, it seems that it is indeed useful for the user to know that a NoUserFoundException is thrown if the user is not found.

In other cases it's less useful. For example, in many cases the fact that a NullPointerException is thrown if a parameter is null is not documented in the Javadoc because it's often somehow implied that a parameter cannot be null.

By the way, Oracle is talking about the throws class appearing after the method declaration, not about the Javadoc. If you decide to document a non-checked exception, it makes sense to use the @throws clause.

like image 194
Hoopje Avatar answered Oct 17 '22 00:10

Hoopje