Do Not Use instanceof to Dispatch Exceptions in Catch Blocks

ID

java.no_instanceof_chain_for_exception_dispatch

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Java

Tags

best-practice, reliability

Description

Reports catch blocks that use instanceof checks on the caught exception variable to dispatch to different exception handlers.

Rationale

When a catch block contains if (e instanceof SomeException) chains, it means the developer is manually dispatching based on exception type. Java’s multi-catch and multiple catch clauses already provide this mechanism in a type-safe, compiler-verified way. Using instanceof bypasses these checks and makes the code harder to maintain.

// Bad -- manual exception dispatch via instanceof
try {
    doWork();
} catch (IOException e) {
    if (e instanceof EOFException) {
        handleEof();
    } else if (e instanceof SocketException) {
        handleSocket();
    }
}

Remediation

Split the catch block into separate clauses for each exception type:

// Good -- separate catch clauses
try {
    doWork();
} catch (EOFException e) {
    handleEof();
} catch (SocketException e) {
    handleSocket();
} catch (IOException e) {
    handleGeneral();
}