Maximize your Laravel blog's potential with SEO best practices and reach 10K monthly clicks on Google.
Preview the course for free
Benjamin Crozat New!
Benjamin Crozat The art of crafting web applications

PHP try & catch: what are exceptions and how to handle them?

Benjamin Crozat — Updated on
Artboard

Hundreds of developers subscribed to my newsletter.
Join them and enjoy free content about the art of crafting websites!

Powered by

Table of contents

PHP try & catch: what are exceptions and how to handle them?

What are exceptions?

Like in many other languages, exceptions in PHP are errors that can be caught and gracefully handled instead of crashing your app.

When to use exceptions?

Use exceptions when you need to gracefully handle an unexpected event instead of just crashing like a fatal error.

Throw exceptions

An exception can be thrown using the throw keyword on an instance of the Exception class. The first parameter is a string describing your error.

Here’s an example where we need to validate the user’s input:

if (empty($_POST['age'])) {
throw new Exception('Your age is missing!');
}

When you run this code, you will see:

Fatal error: Uncaught Exception: Your age is missing!

That’s because we now need to catch our exception and do something with it.

Try catch example to handle exceptions

In PHP, exceptions are handled inside a try and catch block.

In this example, we catch the exception thrown first and display it above our form.

<?php
 
try {
if (empty($_POST['age'])) {
throw new Exception('We need to know how old you are.');
}
 
if ($_POST['age'] < 18) {
throw new Exception('You are too young.');
}
} catch (Exception $exception) {
$error = $exception->getMessage();
}
?>
 
<?php if (! empty($error)) : ?>
<p><?php echo $error; ?></p>
<?php endif; ?>
 
<form method="POST" action="./">
<input type="number" name="age" />
<button type="submit">Send</button>
</form>

OK, but I can do the same without exceptions!

True. But let’s ramp up the difficulty here.

Catch multiple exceptions

Imagine we have a custom exception for each type of error.

<?php
 
// Defining custom exceptions is as simple as that.
class NotFoundException extends Exception {}
 
class ValidationException extends Exception {}
 
try {
if (empty($_SERVER['REQUEST_URI']) || $_SERVER['REQUEST_URI'] !== '/form') {
throw new NotFoundException();
}
 
if (empty($_POST['age'])) {
throw new ValidationException('We need to know how old you are.');
}
 
if ($_POST['age'] < 18) {
throw new ValidationException('You are too young.');
}
 
header('Location: /secret-location');
 
exit;
} catch (NotFoundException $exception) {
http_response_code(404);
 
exit('Page not found.');
} catch (ValidationException $exception) {
$validationError = $exception->getMessage();
}
?>
 
<?php if (! empty($validationError)) : ?>
<p><?php echo $validationError; ?></p>
<?php endif; ?>
 
<form method="POST" action="/form">
<input type="number" name="age" />
<button type="submit">Send</button>
</form>
  1. If the URL in our browser is not /form, we throw a NotFoundException and display a simple ‘Page not found’ in our catch block;
  2. If our age is empty or below 18, we throw a ValidationException and display the error above the form;
  3. Then, we can redirect the user to our secret page. If we get to this stage, no exception was thrown.

As you can see, the clarity of our code just got a step higher, thanks to exceptions.

If you still don’t get why they’re helpful, don’t worry; it’s okay. Time and practice will grant you the rank of master.

The finally block

Introduced with PHP 5.5, the finally block contains code that will always be executed.

try {
// This exception won't be handled.
throw new SomeException;
} finally {
echo 'This code always runs.';
}
 
echo "But this code won't.";

In the example above:

  1. Only one finally block is allowed;
  2. Even when an exception thrown from the try block isn’t handled, the finally block will be executed;
  3. All code coming after the finally block won’t run.

Some good use cases for using the finally block in PHP include:

Catch all exceptions

To catch all exceptions in PHP, you must define a global exception handler with set_exception_handler.

set_exception_handler is usable with anonymous functions.

set_exception_handler(function (Exception $exception) {
// Do what you were doing in your catch block.
});

You can also use a class method (static or not, it doesn’t matter) and tell set_exception_handler which one it is using a callable.

Example:

class ExceptionHandler {
public static function handle(Exception $exception) {
//
}
}
 
set_exception_handler(ExceptionHandler::handle(...));
Recommended

Learning a framework can be overwhelming, but time and execution will make you a master. Here are some best practices to help you toward your goal.

Debugging requires dissecting everything. Here's a list of all the one-line of code built-in ways to print arrays in PHP (and even Laravel-specific helpers).

There are multiple ways to check if an array is empty. Let me tell you about each of them and why and when you should use them.

switch, case, and break. What are all these? When should you use it instead of if? What are its pros and cons?

PHP 8.3 will be released in November 2023, and as usual, you need to be up to date with new features and breaking changes for easier transitions.

Discover how the Tailwind CSS forms plugin can reset your forms to a consistent state across all browsers and make styling easier.

This is the most comprehensive tutorial about Tailwind CSS. Learn how to make front-end development great again.

Knowing which Laravel version you are running is important before you start writing code on a new project. There are multiple ways to do so.

Smaller and even easier than Vue.js, setting up Alpine.js is as easy as copying and pasting a code snippet.

Start leveraging the power of AI today. It enables developers to do incredible things, and many startups build products around it.

Powered by