Exceptions are a special kind of error that require specific code to handle. They are errors that occur after the failure of other code, and PHP offers us ways to gracefully recover and change the normal flow of the script.

A Windows blue screen of death, the ultimate fatal error.

To help wrap your head around exception handling, there are a few keywords you should know:

  • try: Any function that can throw an exception should be inside a try block. This block is used to tell PHP that the code you are trying to run can potentially fail entirely. If nothing fails, the code continues to execute normally.
  • catch: If a failure occurs and an exception is thrown, PHP moves on to execute the code in the catch block, and gives us a useful object with information about what happened. This code block is ignored if no exception was thrown.
  • throw: This keyword is how you manually throw an exception of your own.

Throwing an Exception

Let's throw an exception just so we can see PHP's try-catch mechanism at play:

<?php try { $error = "This is an exception message!"; throw new Exception($error); } catch (Exception $e) { echo("Message: " . $e->getMessage()); echo("File: " . $e->getFile()); echo("Line: " . $e->getLine()); echo("Code: " . $e->getCode()); echo("Trace: " . $e->getTraceAsString()); } ?>
Message: This is an exception message! File: file.php Line: 3 Code: 0 Trace: #0 {main}

Since an exception was thrown inside a try block, PHP automatically ran the catch block and provided us the Exception object that we named $e. From there we extracted some of the information inside the object that can help us understand what went wrong.

Custom Exceptions and Exception Handlers

You can create your own custom exceptions and custom exception handlers in PHP. These are useful for when you want to specialize what exactly should happen when a specific exception is thrown.

Let's create an custom exception handler that is thrown whenever a number that isn't even is passed in by extending PHP's basic Exception class.

<?php class NotEvenNumberException extends Exception { public function error_message() { return "even_number must be an even number!"; } } $even_number = 5; try { if ($even_number % 2 != 0) { throw new NotEvenNumberException(); } } catch (NotEvenNumberException $nene) { echo("Error Message: " . $nene->error_message()); } ?>
Error Message: even_number must be an even number!

As expected, because the value for $even_number wasn't actually an even number, we threw our custom exception, NotEvenNumberException. Then inside our catch block we are watching for any NotEvenNumberException that are thrown, and once one was, our $nene object had access to the custom function we defined, error_message().

Global Exception Handlers

You can set a global exception handler to catch any exceptions that aren't caught by other parts of your code. This is useful because it allows you to ensure that at least some code will run if an exception is thrown.

<?php function customExceptionHandler($exception) { echo('Exception Message: ' . $exception->getMessage()); } set_exception_handler('customExceptionHandler'); throw new Exception('A random exception!'); echo('hi!'); ?>
Exception Message: A random exception!

Notice how you didn't see the echo function execute? Because we still didn't catch the exception, the script still terminated. The script will only continue to execute after an exception is thrown if the exception is caught using a try-catch block like the ones shown before.

We hope this lesson has helped you become familiar with exceptions in PHP, how to catch them, and what to do once you've caught one!

Next Lesson »
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.