All articles

Find and fix PHP problems

Throw a PHP Exception When an Operation Fails, Then Catch It at the Caller

See where to throw PHP exceptions, when to let them propagate, how to catch each failure, and how to close a file handle with finally.

Editorial illustration for Throw a PHP Exception When an Operation Fails, Then Catch It at the Caller

When a function cannot complete its job, throw an exception at the failure rather than returning a result that looks successful. An intermediate caller can leave it alone; a caller that knows what response to give can catch it. The practical choice is where handling becomes useful: input can prompt a correction, while an operation failure may need a fixed message that does not expose internal details.

Throw at the point of failure

This self-contained example simulates an operation that makes a confirmation. An empty label is invalid input. The label unavailable stands for an operation that cannot complete; it is a teaching scenario, not a real service call or saved record. The example can go in a PHP file beginning with <?php.

<?php
function createConfirmation($label)
{
    if ($label === '') {
        throw new InvalidArgumentException('A label is required.');
    }

    if ($label === 'unavailable') {
        throw new RuntimeException('Confirmation service unavailable.');
    }

    return 'Confirmation for ' . $label;
}

function submitRequest($label)
{
    return createConfirmation($label);
}

function responseFor($label)
{
    try {
        return 'OK: ' . submitRequest($label);
    } catch (InvalidArgumentException $e) {
        return 'Please enter a label.';
    } catch (RuntimeException $e) {
        return 'Sorry, your request could not be completed.';
    }
}

echo responseFor('Ada') . "\n";
echo responseFor('') . "\n";
echo responseFor('unavailable') . "\n";

For those three calls, the intended output is:

OK: Confirmation for Ada
Please enter a label.
Sorry, your request could not be completed.

The success path returns a confirmation through submitRequest() to responseFor(). On either failure path, execution does not continue after the throw in createConfirmation(). PHP looks for a matching catch, including in callers farther up the call stack. That is why neither failure produces an OK: response. See the exception-handling explanation for the caller-to-caller search.

The example uses exact string comparisons so each call has a clear purpose. In an actual function, place the invalid-input check where the input is evaluated and throw the operation-failure exception where that failure is detected. Do not infer that this simulated unavailable value checks the health of anything external.

Catch where a useful response is possible

responseFor() has enough context to give different answers. Its separate catch blocks turn invalid input into a request for correction and an operation failure into a fixed response. The runtime exception's message is available on the exception object, but this example deliberately does not print it to the caller. A useful user-facing answer does not have to disclose the reason recorded at the failure site.

The try surrounds the call that may throw. If submitRequest() returns, the function adds OK: and returns the result. If an exception reaches either catch, that catch returns its own response instead. PHP permits multiple catches for different exception classes, as illustrated by the separate-catch example.

Let an intermediate call propagate

submitRequest() has no way to correct a blank label or finish a failed operation, so it has no catch. It also does not replace either exception with a success value. The boundary caller receives the original failure type and can choose the corresponding response.

If an intermediate function must record a failure before passing it on, it can catch and rethrow the same exception:

function submitAndRecordFailure($label)
{
    try {
        return createConfirmation($label);
    } catch (InvalidArgumentException $e) {
        // Record the failure here if this function has a recorder.
        throw $e;
    } catch (RuntimeException $e) {
        // Record the failure here if this function has a recorder.
        throw $e;
    }
}

This variant only marks where recording code would go; it does not record anything as written. Use throw $e when there is actual work to do in the catch. Otherwise, the catch adds nothing, and the simpler submitRequest() already lets the exception travel to the caller.

Use finally for cleanup

An opened file handle needs closing whether the protected work returns or throws. The following separate example checks that the open succeeded before entering try, so finally only closes a handle that was opened:

function workWithFile($path, $shouldFail)
{
    $handle = fopen($path, 'r');
    if ($handle === false) {
        throw new RuntimeException('Could not open the file.');
    }

    try {
        if ($shouldFail) {
            throw new RuntimeException('Could not finish the work.');
        }

        return 'Work completed.';
    } finally {
        fclose($handle);
    }
}

Pass a readable file path to focus on the two paths inside try: a normal return or the simulated failure. In either case, finally closes the opened handle. If opening fails, there is no handle to close, and the function throws before entering try. The finally syntax requires PHP 5.5 or later; its cleanup role is described in this PHP exception tutorial.

← All articles