Try...Catch

try

(No version information available, might only be in Git)

A try block delimits a segment of code which might throw a Throwable error that needs handling. A try block must have at least one corresponding catch or finally block.

When a Throwable error is thrown in a try block PHP will attempt to find the first matching catch block to handle the error. If none can be found, it will unwind the call stack until one is found or a global error handler is reached.

Note:

It's possible to add a handler for any uncaught Throwable with set_exception_handler(). This is similar to wrapping the entire code in a try-catch block.

catch

(No version information available, might only be in Git)

A catch block defines how to respond to a thrown Throwable error. It specifies one or more subclasses of Throwable (most commonly Exception) it can handle, and optionally a variable to which to assign the exception.

The first catch block that matches the class of the thrown Throwable object will handle the error. Normal execution resumes after the catch block without entering any other matching catch blocks.

Example #1 Catching an Exception

<?php
try {
    throw new Exception('Error');
} catch (Exception $e) {
    echo 'Caught exception: ', $e->getMessage(), "\n";
}

// Continue execution
echo "Hello World\n";

The above example will output:

Caught exception: Error
Hello World

As of PHP 7.1.0, a catch block may specify a union of Throwable subclasses that the block should handle using the pipe (|) character. This is useful for when different exceptions from different class hierarchies are handled the same.

Example #2 Catching a union of classes to handle

<?php

class MyException extends Exception { }

class MyOtherException extends Exception { }

class Test {
    public function testing() {
        try {
            throw new MyException();
        } catch (MyException | MyOtherException $e) {
            var_dump(get_class($e));
        }
    }
}

$foo = new Test;
$foo->testing();

The above example will output:

string(11) "MyException"

Multiple catch blocks can be used to handle different classes of Throwable errors in different ways. Normal execution (when no error is thrown within the try block) will continue after that last catch block defined in sequence.

Example #3 Multiple catch blocks

<?php
try {
    do_something_io_related();
} catch (FileNotFoundException $e) {
    // Only catch FileNotFoundException and do something in this case
} catch (MissingPermissionException $e) {
    // Only catch MissingPermissionException and do something different in this case
}

Throwables can be thrown (or re-thrown) within a catch block. If nothing is thrown, the execution resumes as normal.

Example #4 Nested Exception

<?php

class MyException extends Exception { }

class Test {
    public function testing() {
        try {
            try {
                throw new MyException('foo!');
            } catch (MyException $e) {
                // rethrow it
                throw $e;
            }
        } catch (Exception $e) {
            var_dump($e->getMessage());
        }
    }
}

$foo = new Test;
$foo->testing();

The above example will output:

string(4) "foo!"
Caution

Throwing an object inside a catch block will not be caught by an adjacent catch block.

Example #5 Sequential catch blocks

<?php

class A extends Exception {}
class B extends Exception {}

try {
    throw new A;
} catch(A $e) {
    throw new B;
} catch(B) {
    echo 'Hello';
}

The above example will output something similar to:

Fatal error: Uncaught B in /in/K8Tl9:9
Stack trace:
#0 {main}
  thrown in /in/K8Tl9 on line 9

As of PHP 8.0.0, the variable name for a caught Throwable is optional. If not specified, the catch block will still execute but will not have access to the thrown object.

Example #6 Omitting the caught variable

Only permitted as of PHP 8.0.0.

<?php

class SpecificException extends Exception {}

function test() {
    throw new SpecificException('Oopsie');
}

try {
    test();
} catch (SpecificException) {
    print "A SpecificException was thrown, but we don't care about the details.";
}

The above example will output:

A SpecificException was thrown, but we don't care about the details.
+add a note

User Contributed Notes

There are no user contributed notes for this page.
To Top