Empty Try Block

ID

php.empty_try_block

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Php

Tags

CWE:1071, exception-handling, reliability

Description

Reports try blocks whose body has no statements. An empty try block protects no code, so its catch and finally clauses can never observe a real failure. A body that contains only comments is also treated as empty, because comments are not executable statements.

Rationale

A try block exists to guard the statements inside it. When the body is empty the construct guards nothing: the catch clauses are unreachable and the whole structure is dead code that only adds noise and misleads the reader into thinking some risky operation is being protected. It usually means the guarded code was removed or never added.

<?php
function build(): void
{
    try { } catch (Exception $e) {              // FLAW — try guards no code
        error_log($e->getMessage());
    }

    try {
        doWork();                               // OK — a real statement is guarded
    } catch (Exception $e) {
        error_log($e->getMessage());
    }
}

Remediation

Move the statements that can fail inside the try block, or remove the try/catch construct if there is nothing left to guard.