Skip to content
This repository was archived by the owner on May 28, 2022. It is now read-only.
This repository was archived by the owner on May 28, 2022. It is now read-only.

Java coding standard: document when to use/not use checked exceptions #102

@pyokagan

Description

@pyokagan

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:

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions