Do Not Throw Raw java.lang.Exception

ID

java.throw_specific_exception

Severity

info

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Java

Tags

CWE:397, reliability

Description

Reports throw new Exception(…​) statements where the raw java.lang.Exception is instantiated and thrown directly.

Rationale

java.lang.Exception is the root of the checked exception hierarchy. Throwing it directly provides no information about the nature of the error, forces callers to write catch (Exception e) which swallows every checked exception, and makes it impossible to distinguish between unrelated failure modes. Every throw should use the narrowest exception type that accurately describes the problem.

// Bad -- callers cannot distinguish error conditions
if (age < 0) {
    throw new Exception("invalid age");
}

This rule does not flag subclasses of Exception (e.g. IOException, IllegalArgumentException) nor rethrows of an existing variable (throw e;).

Remediation

Choose (or create) a specific exception type:

// Good -- precise and catchable
if (age < 0) {
    throw new IllegalArgumentException("age must be non-negative: " + age);
}