Safeguard
Application Security•

CWE-460 Improper Cleanup on Thrown Exception

Exceptions skip the code that releases locks and resources. CWE-460 explained with a Java thread lock example and the fix.

Safeguard Security Team
2 min read

CWE-460 happens when a product does not clean up its state, or cleans it up incorrectly, when an exception is thrown. The result is an unexpected state or control flow.

MITRE lists C, C++, Java and C# as the affected languages.

How it happens

As functions and loops grow complicated, cleanup is needed at several points. An exception jumps over the code that would have run that cleanup. MITRE's example is a Java method that sets a thread lock flag while working and clears it afterward:

public static final boolean doStuff() {
    boolean threadLock;
    boolean truthvalue = true;
    try {
        while (/* some condition */) {
            threadLock = true;
            // do some stuff to truthvalue
            threadLock = false;
        }
    } catch (Exception e) {
        System.err.println("You did something bad");
        if (something) return truthvalue;
    }
    return truthvalue;
}

If an exception fires between the two assignments, the method may return with the lock still set, so a thread is left locked accidentally.

What an attacker gains

MITRE lists the consequence as varying by context: the code could be left in a bad state. A stuck lock or unreleased resource can block other work and become a denial of service.

How to find it

MITRE says static analysis (SAST) can find some instances by modeling data flow. Review every try block that acquires something and ask what state exists if control leaves early. Inject failures in tests to see what stays held.

How to fix it

MITRE's advice: if you break from a loop or function by throwing an exception, make sure cleanup happens, or exit the program. Use exceptions sparingly.

In Java, put release logic in finally:

try {
    threadLock = true;
    // work
} finally {
    threadLock = false;
}

Quick check

Where should lock release code go?

In a finally block, so it runs whether the work succeeds or throws.

Sources

Never miss an update

Weekly insights on software supply chain security, delivered to your inbox.

Self-healing security runs on Safeguard.

Your first fix PR is minutes away.

No sales call required, even your agent can complete the purchase over MCP.