-
Notifications
You must be signed in to change notification settings - Fork 19
Java coding standard: document when to use/not use checked exceptions #102
Description
Unchecked exceptions are used for:
- Errors which are unrecoverable or very hard to recover from (e.g. out of memory)
- Programmer errors (e.g. division by zero, null pointer exceptions)
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:
if (fileExists(filename)) {
readFromFile(filename);
} else {
print(filename + " does not exist");
}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.
try {
readFromFile(filename);
} catch (FileNotExistsException e) {
print(filename + "does not exist");
}Example 2: Maintaining invariants on a list
The addressbook-level4 has lots of instances of:
try {
uniqueList.add(item);
} catch (DuplicateItemException e) {
print("Item is a duplicate");
}Following the rules set forth above, we can see that the DuplicateItemException is completely avoidable since the program is completely in control of the uniqueList, and thus can properly ensure that all preconditions are met. The proper implementation should be:
if (!uniqueList.contains(item)) {
uniqueList.add(item);
} else {
print("Item is a duplicate");
}References:
- https://stackoverflow.com/a/19061110
Checked Exceptions should be used for expected, but unpreventable errors that are reasonable to recover from. Unchecked Exceptions should be used for everything else.
- https://docs.oracle.com/javase/tutorial/essential/exceptions/runtime.html
Here's the bottom line guideline: If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception