google / google/error-prone

Warn about catch blocks with a needlessly large scope

Open
#517 0 comments 0 reactions 0 assignees View on GitHub
Type-NewCheck
Dominant language
Java
Stars
7.2k
Forks
820
Avg merge
5h 9m
Merged PRs (30d)
50

Description

(I apologize if this feature already exists or already has been requested; I searched but did not find.)

This request is in the context of [a discussion on the guava-discuss mailing list](https://groups.google.com/forum/#!topic/guava-discuss/QvModYS4uIM) and [the associated Guava wiki page](https://goo.gl/Ivn2kc). Would it be possible for Error Prone to warn about `catch` blocks catching `Throwable` or `Exception` in cases where a scope reduction is possible? Some rationale (this list is unlikely to be exhaustive):

- Catching `Exception` when one actually only wishes to catch specific subtypes of `Exception`:
- By explicitly enumerating those one or more subtypes, one is forced to explicitly consider additional exceptions thrown inside the `try` block as a result of refactoring. This prevents bug from silently sneaking in.
- As a special case, it forces one to explicitly handle `InterruptedException`s if applicable.
- If only `RuntimeException`s are thrown from inside the `try` block, the block should be removed completely, or `catch RuntimeException` should be declared instead, to make explicit something "funny" is going on.
- Catching `Throwable` when actually one only wants to catch `Exception`s:
- The points above also apply here.
- Additionally, one seldom wants to catch all `Error`s. And when one does, they should generally be treated specially.

Additionally, consider a `try` block in which both `Exception` and `InterruptedException` are thrown. In this case Error Prone could check that the `InterruptedException` is handled explicitly, either in a `catch` block of its own, or an `instanceof` check in the `catch Exception` block.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.