Uncaught Throw Global

ID

php.uncaught_throw_global

Severity

high

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Php

Tags

exception-handling, reliability

Description

Reports a throw statement at the global (top-level) scope of a script that is not wrapped in a try/catch. Such an exception has no handler in the same file and propagates straight to PHP’s default uncaught-exception handler.

Rationale

A throw at global scope that nothing catches aborts the script with a fatal error. Depending on configuration it may print a stack trace to the response, disclosing internal paths and class names, and it leaves no opportunity to clean up, log a friendly message or return a controlled status. A throw inside a function or method is different: the caller chooses how to handle it. A throw wrapped in a try with a catch is already handled.

<?php
throw new RuntimeException('boot failed');   // FLAW — escapes to the default handler, fatal error

try {
    throw new RuntimeException('inside try'); // OK — a catch clause handles it
} catch (RuntimeException $e) {
    error_log($e->getMessage());
}

function bootstrap(): void
{
    throw new RuntimeException('to caller');  // OK — inside a function, the caller decides
}

Remediation

Wrap the throwing code in a try/catch that logs the failure and exits cleanly, or move the logic into a function or method whose callers are responsible for handling the exception. At the very least register a global exception handler so the program degrades gracefully.