Skip to content
FLAVIO COPES
flaviocopes.com
2026

How to use exceptions in PHP

By

Learn how to use exceptions in PHP with try and catch blocks, inspect the error with getMessage, catch specific types, and run cleanup code in finally.

~~~

Sometimes errors are unavoidable.

Something completely unpredictable happens.

But many times, we can think ahead, and write code that can intercept an error, and do something sensible when this happens. Like showing a useful error message to the user, or try a workaround.

We do so using exceptions.

Exceptions are used to make us, developers, aware of a problem.

We wrap some code that can potentially raise an exception into a try block, and we have a catch block right after that. That catch block will be executed if there’s an exception in the try block:

try {
  //do something
} catch (Throwable $e) {
  //we can do something here if an exception happens
}

Notice that we have an Exception object $e being passed to the catch block, and we can inspect that object to get more information about the exception, like this:

try {
  //do something
} catch (Throwable $e) {
  echo $e->getMessage();
}

Let’s do an example.

For example by mistake I divide a number by zero:

echo 1 / 0;

This will trigger a fatal error and the program is halted on that line:

Fatal error message showing Uncaught DivisionByZeroError with stack trace when dividing by zero

Wrapping the operation in a try block and printing the error message in the catch block, the program ends successfully, telling me the problem:

try {
  echo 1 / 0;
} catch (Throwable $e) {
  echo $e->getMessage();
}

Browser output showing Division by zero error message caught and displayed by the try-catch block

Of course this is a simple example but you can see the benefit: I can intercept the issue.

Each exception has a different class. For example we can catch this as DivisionByZeroError and this lets me filter the possible problems and handle them differently.

I can have a catch-all for any throwable error at the end, like this:

try {
  echo 1 / 0;
} catch (DivisionByZeroError $e) {
  echo 'Ooops I divided by zero!';
} catch (Throwable $e) {
  echo $e->getMessage();
}

Browser output showing custom error message Ooops I divided by zero from specific DivisionByZeroError catch block

And I can also append a finally {} block at the end of this try/catch structure to execute some code after the code is either executed successfully without problems, or there was a catch:

try {
  echo 1 / 0;
} catch (DivisionByZeroError $e) {
  echo 'Ooops I divided by zero!';
} catch (Throwable $e) {
  echo $e->getMessage();
} finally {
  echo ' ...done!';
}

Browser output showing custom error message with finally block execution displaying done at the end

You can use the built-in exceptions provided by PHP but you can also create your own exceptions.

Tagged: PHP · All topics
~~~

Related posts about php: