Code has been added to clipboard!

Using PHP Try Catch Throw Techniques to Handle Exceptions

Reading time 8 min
Published Aug 8, 2017
Updated Oct 2, 2019

Though you are already familiar with PHP error handling, stopping the script isn't always the best solution. PHP 5 introduced new ways to manage errors, called PHP try catch and throw methods and exceptions.

A PHP exception is a specified error that the system can catch and handle. It means you can make the code execution continue even if errors are detected. The principle of PHP exception handling is different from that of PHP error handling because it is object-oriented (based on creating objects that contain both data and functions).

With exceptions and their manipulation, you can modify the normal flow of your script in case a specific error occurs. PHP try catch functions will create a way to prevent the code from stopping when it faces issues.

PHP try catch: Main Tips

  • Exceptions were introduced in the PHP version 5, when the standard error-handling proved not to be enough for certain cases.
  • The main functions used for handling exceptions are PHP try catch and throw.

Methods to Manipulate Exceptions

Usually, when an exception is triggered, the system goes through the following steps:

  • Saves the current state of the script.
  • Switches execution to the pre-defined function for exception handling.

Next steps depend on the specific situation. The handler may continue the execution from the script state saved earlier, terminate the code flow entirely or keep going from a different line of the code.

In this tutorial, we will demonstrate the following methods of using PHP exceptions to handle errors.

Note: Exceptions are specifically meant for PHP error handling, not for jumping to another point in the script.

Basic Usage

Upon throwing the exception, PHP will stop the normal script flow and look for the first catch() block it encounters, which it will execute. If there is no such block of code, a fatal error will occur, with the message of Uncaught Error.

Try to PHP throw exception without a catch() statement:

Example
<?php
//creating a function, which throws an exception
function check_num($number) {
  if($number>1) {
    throw new Exception("The value has to be 1 or lower");
  }
  return true;
}

//triggering the exception
check_num(3);
?>

You will see this warning message displayed:
Fatal error: Uncaught exception 'Exception'
with message 'Value must be 1 or below' in C:\webfolder\test.php:6
Stack trace: #0 C:\webfolder\test.php(12):
checkNum(28) #1 {main} thrown in C:\webfolder\test.php on line 6

try, throw and catch

If we don't want our web application to crash each time an exception is caught, we have to write a script to handle the exception. A properly executed script for handling an exception should include:

  • try block is for the portion of code where exception might occur. If the exception doesn't trigger, the code runs as normal. If it does, it is thrown.
  • throw block is used to trigger an exception. Every throw has to have at least a single catch block.
  • catch - this block retrieves the exception and generates the object that holds its data.

In the example below you can view the triggering of an exception (we have all the necessary blocks of code):

Example
<?php
  //creating a function containing a potential exception
  function checkNumber($number) {
    if($number > 1) {
      throw new Exception('The value has to be 1 or lower');
    }
    return true;
  }

  //triggering the exception inside a try()
  try {
    checkNumber(2);
    //In case the exception gets thrown, this is the message that is shown.
    echo 'The value is 1 or lower';
  } catch(Exception $e) {
    //catching the exception
    echo 'Message: ' .$e->getMessage();
  }
?>

This is the error we get now:
Message: Value must be 1 or below

More Details on Code Example

In the example above, we threw an exception and handled it with a catch() block. Let's break down the process step by step:

  • The function called check_num() is defined. Its job is to check whether a value is greater than 1. If this condition is met, we PHP throw exception.
  • The function we just created gets called in a try() block.
  • Inside the function, an exception gets thrown.
  • catch() receives the thrown exception and creates an object called $e that holds the information on the exception.
  • We echo the error message from the exception by calling $e->getMessage() from the object, containing data on exceptions.

While the rule says every exception must have a catch(), there is a way to go around it. To do that, we must learn how to define a top tier exception handler class.

Custom Exception Class

To make a custom exception handler, you must create a class, containing functions meant for handling exceptions in PHP once they are triggered. This class has to be an exception class's extension. It will have all of the original properties of the exception class, but you can provide it with custom functions.

You can see how to create a custom exception class in the example below:

Example
<?php
  class customException extends Exception {
    public function error_message() {
      //defining the error message
      $error_msg = 'Error caught on line '.$this->getLine().' in '.$this->getFile()
        .': <b>'.$this->getMessage().'</b> is no valid E-Mail address';
      return $error_msg;
    }
  }

  $email = "someonesomeone@example...com";

  try {
    //checking if
    if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) {
      //throwing an exception in case email is not valid
      throw new customException($email);
    }
  } catch (customException $e) {
    //displaying a custom message
    echo $e->error_message();
  }
?>

This new class is an almost identical copy of the original exception class. However, now it has a custom error_message() function. Since it has all the methods and properties of the original class, we can use every function contained in a normal exception class, such as GetLine(), GetFile(), GetMessage().

Code Explained

The code example above throws an exception, which is caught using a custom exception class:

  • The class custom_exception() is made as an extension of the original class, inheriting every property and method from the original.
  • Function error_message() is created. By using this function, we make the code return an error message in case the e-mail address is invalid.
  • $email is a string, which is not a valid e-mail address.
  • A try() block executes and an exception is thrown.
  • The catch() block displays an error message.

Usage of Multiple Exceptions

By using multiple exceptions, you can check multiple conditions at once. To do that, you should use either several if..else code blocks, a switch, or multiple exceptions. Keep in mind that each of these exceptions may use its own class and display their error messages:

Example
<?php
  class customException extends Exception {
    public function error_message() {
      //error message
      $error_msg = 'Error caught on line '.$this->getLine().' in '.$this->getFile()
        .': <b>'.$this->getMessage().'</b> is no valid E-Mail address';
      return $error_msg;
    }
  }

  $email = "someonesomeone@example.com";

  try {
    //check if
    if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) {
      //throwing an exception in case email is not valid
      throw new customException($email);
    }
    //checking for "example" in mail address
    if(strpos($email, "example") !== FALSE) {
      throw new Exception("$email contains'example'");
    }
  }
  catch (customException $e) {
    echo $e->error_message();
  }
  catch(Exception $e) {
    echo $e->getMessage();
  }
?>

More Information on Example

In the example above, we saw that two particular conditions are tested. In case they both are not met, an exception is thrown:

  • The class custom_exception() is made as an extension of the original class, inheriting every property and method from the original.
  • The error_message() function is created. This function returns an error message if an e-mail address is invalid.
  • $email is a string, which is a valid e-mail address, containing the word example.
  • A try() block executes, but an exception isn't thrown.
  • On checking the second condition, an exception is thrown, since the $email variable contains the example string value.
  • The catch() block displays an error message.

In case the exception that was thrown belongs to the custom_exception class which had no specific catch, the base exception catch would handle the exception.

Re-Throwing Exceptions

At times, upon throwing an exception, you might want to handle it in a different than the standard way. You can throw the exception again within your catch() block.

Such script is meant to hide system errors from users of the web application. The coder may want to be aware of system errors, but users don't (and shouldn't) care about that. If you want to make error message user-friendly, you may re-throw the exception to change the message:

Example
<?php
  class customException extends Exception {
    public function error_message() {
      //error message
      $error_msg = $this->getMessage().' is no valid E-Mail address.';
      return $error_msg;
    }
  }

  $email = "someonesomeone@example.com";

  try {
    try {
      //checking for "example" in mail address
      if(strpos($email, "example") !== FALSE) {
        //throwing an exception if email is not valid
        throw new Exception($email);
      }
    } catch(Exception $e) {
      //re-throwing exception
      throw new customException($email);
    }
  } catch (customException $e) {
    //display custom message
    echo $e->error_message();
  }
?>

Details on Example

The code example above tests whether the entered email-address has the string example as its value. If the string is found, the exception is re-thrown:

  • The class custom_exception() is made as an extension of the original class, inheriting every property and method from the original.
  • The error_message() function is created. This function returns an error message if an e-mail address is invalid
  • $email is a string, which is a valid e-mail address, containing the word example.
  • The try() contains another try() block, which is used for re-throwing our exception.
  • An exception is thrown since the $email variable contains the example string value.
  • The exception is caught, and a custom_exception is then thrown.
  • This exception displays a user friendly error message.

In case the exception doesn't run into a catch() block in its current try() block, it may search for a catch() in higher levels.

Top Level Exception Handler

The function called set_exception_handler() makes a user-defined function meant to handle every uncaught exception. Let's look at the example:

Example
<?php
  function myException($exception) {
    echo "<b>Exception is </b> " . $exception->getMessage();
  }

  set_exception_handler('myException');

  throw new Exception('Uncaught Exception has been caught');
?>

This is the output we should get from the code above:
Exception: Uncaught Exception occurred

Note: In the code above there was no catch() block. All of these exceptions were handled by the top level exception handler we set.

PHP try catch: Summary

  • Previous PHP versions (before PHP 5) had errors but not exceptions.
  • Exceptions are handled using try(), catch() and throw() functions.
  • It's possible to use multiple exceptions and multiple catch() blocks at the same time.
  • You may write most of the script in the try() block to handle all the exceptions that may occur.
  • Exceptions can be thrown in a catch() block located inside a try() block.
Tutorial
Introduction
Installation
Syntax
Variable
Superglobals
Data Types
String
Array
Multidimensional Array
Sort Array
Constant
Operators
Cookies
Sessions
DateTime
Error Handling
Exception Handling
File
Write and Create File
File Open, Read and Close
File Upload
Filtering
Redirecting
Advanced Filters
Forms
Form Required Field
Validate Email/URL
Form Validation
Form Action
Function
Prepared Statements
JSON
Calendar
ZIP File
FTP
HTTP Response
DateTime Functions
Error Functions
File Function
Filter
Math Functions
Mail Function
Miscellaneous Functions
Date Format
String Functions
Array Functions
Directory Functions
MySQL Database
MySQL Connection
MySQL Create Database
MySQL Create Table
MySQL Delete Data
MySQL Insert Data
MySQL Get Last Record ID
MySQL Insert Multiple Records
MySQL Select Data
MySQL Limit Data
MySQL Update Data
MySQLi Functions
AJAX and MySQL
AJAX Search
AJAX Poll
RSS Reader
Read XML File in PHP
XML Parser
SimpleXML Parser
SimpleXML: Node and Attribute
Expat XML Parser
DOMDocument
Libxml Functions
SimpleXML Functions
XML Parsing Functions
PHP isset
PHP echo and print
PHP if else and elseif
PHP switch case
PHP include File
PHP while Loop
PHP for and foreach
PHP mail()
PHP explode()
PHP substr()
PHP str_replace()
PHP array_push
PHP count()