-
Notifications
You must be signed in to change notification settings - Fork 19
Java coding standard: document when to use/not use checked exceptions #102
Comments
Okay, maybe this could be better explained as: "accessing a resource which the program has no control over" 🤔 |
@damithc @Zhiyuan-Amos @yamgent Thoughts? There really needs to be a consistent approach inside addressbook's code base. |
Yup I agree with the this. As such, I suppose |
Won't that hide programmer errors? e.g. if the return value is accidentally not checked. |
if (!uniqueList.contains(item)) {
uniqueList.add(item);
} else {
print("Item is a duplicate");
}
|
Yes. And right, this will need to be elaborated on. I think I'll just open a PR soonish.
Right, a fully specified API definition will define the preconditions/postconditions of the method, what kind of exceptions are thrown etc.
I think it should use a checked exception. Otherwise, |
I support the proposal as it sounds right in principle. Let's give it a try and see if holds up well in practice too. |
To add: checked exceptions, when thrown, should leave the program in a documented state. This state needs to be documented in the javadoc of all methods which has the "throws" declaration. This is needed to guide callers on recovering from the exception, It is assumed that unchecked exceptions, when thrown, leave the program in an undefined state, and thus not worth the effort to recover from. |
Unchecked exceptions are used for:
Checked exceptions are for errors which are (1) recoverable (2) even after doing everything in our power to predict/prevent the possible errors, still cannot be predicted without actually running the operation because the resource the operation in operating on is not within the program's control.
As the SO answer notes, the Java stdlib is not very consistent in its use of checked/unchecked exceptions either, which contributes the confusion.
Example 1: Reading from a file
We will be temped to do the following when attempting to read from a file:
However, this is not correct. The file might be deleted in between the "fileExists" and "readFromFile" calls by another process.
In this case, we won't truly know if the file exists unless we actually read from the file. Thus, it is proper for
readForFile
to throw a checked exception, i.e.Example 2: Maintaining invariants on a list
The addressbook-level4 has lots of instances of:
Following the rules set forth above, we can see that the
DuplicateItemException
is completely avoidable since the program is completely in control of theuniqueList
, and thus can properly ensure that all preconditions are met. The proper implementation should be:References:
The text was updated successfully, but these errors were encountered: