Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

PHP exception handling


May 11, 2021 PHP


Table of contents


PHP exception handling

Exceptions are errors that occur when a program is running as expected, allowed to occur, but are an abnormal condition, an error that should not have occurred, but still occur, a logical and business process error, not a compilation or syntax error.

Exceptions are used to change the normal flow of the script when a specified error occurs.


What is an exception

PHP 5 provides a new way to handle object-oriented errors.

Exception handling is used to change the normal flow of the script when a specified error (exception) condition occurs. This condition is called an exception.

When an exception is triggered, it usually occurs:

  • The current code state is saved
  • Code execution is switched to a predefined (custom) exception processor function
  • Depending on the situation, the processor may restart the execution of the code from the saved code state, terminate the script execution, or continue with the script from another location in the code

We'll show you different ways to handle errors:

  • The basic use of exceptions
  • Create a custom exception processor
  • Multiple exceptions
  • Throw the exception again
  • Set up the top-level exception processor

Note: Exceptions should only be used in the wrong situation and should not be used to jump to another location in the code at a specified point.


The basic use of exceptions

When an exception is thrown, the subsequent code does not continue and PHP attempts to find a matching "catch" block of code.

If the exception is not caught and set_exception_handler() is not handled accordingly, a serious error (fatal error) occurs and an error message is output for "Uncaught Exception" (uncaught exception).

Let's try to throw an exception without catching it:

<?php
 //create function with an exception
 function checkNum($number)
 {
 if($number>1)
 {
 throw new Exception("Value must be 1 or below");
 }
 return true;
 }

 //trigger exception
 checkNum(2);
 ?> 

The above code gets an error like this:

Fatal error : Uncaught exception 'Exception'
with message 'Value must be 1 or below' in C:webfoldertest.php:6
Stack trace: #0 C:webfoldertest.php(12):
checkNum(28) #1 {main} thrown in C:webfoldertest.php on line 6

Try, throw, and catch

To avoid errors in the above instance, we need to create the appropriate code to handle the exception.

The appropriate handling exception code should include:

  1. Try - Functions that use exceptions should be inside the "try" block of code. I f no exception is triggered, the code continues as usual. However, if an exception is triggered, an exception is thrown.
  2. Throw - specifies how to trigger an exception. Each "throw" must correspond to at least one "catch".
  3. Catch - The "catch" block of code catches the exception and creates an object that contains the exception information.

Let's trigger an exception:

<?php
 //create function with an exception
 function checkNum($number)
 {
 if($number>1)
 {
 throw new Exception("Value must be 1 or below");
 }
 return true;
 }

 //trigger exception in a "try" block
 try
 {
 checkNum(2);
 //If the exception is thrown, this text will not be shown
 echo 'If you see this, the number is 1 or below';
 }

 //catch exception
 catch(Exception $e)
 {
 echo 'Message: ' .$e->getMessage();
 }
 ?> 

The above code will get an error like this:

Message: Value must be 1 or below

Example explanation:

The above code throws an exception and catches it:

  1. Create a checkNum() function. I t detects whether the number is greater than 1. If so, throw an exception.
  2. Call the checkNum() function in the "try" block of code.
  3. Exceptions in the checkNum() function are thrown.
  4. The "catch" block of code receives the exception and creates an object that contains the exception information ($e).
  5. The error message from the exception $e output by calling the error message from this exception object, or by calling the error-to-getMessage().

However, in order to follow the "one catch per throw" principle, you can set up a top-level exception processor to handle missed errors.


Create a custom Exception class

Creating custom exception handlers is easy. W e simply created a specialized class that can call its functions when an exception occurs in PHP. The class must be an extension of the exception class.

This custom exception class inherits all the properties of PHP's exception class, to which you can add custom functions.

Let's start creating the exception class:

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

 $email = "[email protected]";

 try
 {
 //check if
 if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE)
 {
 //throw exception if email is not valid
 throw new customException($email);
 }
 }

 catch (customException $e)
 {
 //display custom message
 echo $e->errorMessage();
 }
 ?> 

This new class is a copy of the old exception class, plus the errorMessage() function. Just because it's a copy of the old class, so it inherits properties and methods from the old class, we can use methods of the exception class, such as getLine(), getFile(), and getMessage().

Example explanation:

The above code throws an exception and catches it with a custom exception class:

  1. The customException() class was created as an extension of the old exception class. This inherits all the properties and methods of the old exception class.
  2. Create an errorMessage() function. If the e-mail address is illegal, the function returns an error message.
  3. Set $email variable to an illegal e-mail address string.
  4. Execute the "try" block of code and throw an exception because the e-mail address is illegal.
  5. The catch block catches the exception and displays an error message.

Multiple exceptions

You can use multiple exceptions for a single script to detect multiple situations.

You can use more than one if: . E lse blocks of code, or a switch block of code, or nesting multiple exceptions. These exceptions can use different exception classes and return different error messages:

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

 $email = "[email protected]";

 try
 {
 //check if
 if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE)
 {
 //throw exception if email is not valid
 throw new customException($email);
 }
 //check for "example" in mail address
 if(strpos($email, "example") !== FALSE)
 {
 throw new Exception("$email is an example e-mail");
 }
 }

 catch (customException $e)
 {
 echo $e->errorMessage();
 }

 catch(Exception $e)
 {
 echo $e->getMessage();
 }
 ?> 

Example explanation:

The above code tests two conditions and throws an exception if neither of them is true:

  1. The customException() class was created as an extension of the old exception class. This inherits all the properties and methods of the old exception class.
  2. Create an errorMessage() function. If the e-mail address is illegal, the function returns an error message.
  3. Set $email variable to a string that is a valid e-mail address but contains the string "example".
  4. Execute the "try" block of code, and under the first condition, no exceptions are thrown.
  5. Because e-mail contains the string "example," the second condition triggers an exception.
  6. The catch block catches the exception and displays the appropriate error message.

If the customException class throws an exception, but does not catch customException, and only base exception is caught, the exception is handled there.


Throw the exception again

Sometimes, when an exception is thrown, you may want to handle it in a different way than the standard. You can throw an exception again in a "catch" block of code.

The script should hide system errors from the user. S ystem errors may be important to programmers, but users are not interested in them. To make it easier for users to use, you can again throw exceptions with user-friendly messages:

<?php
 class customException extends Exception
 {
 public function errorMessage()
 {
 //error message
 $errorMsg = $this->getMessage().' is not a valid E-Mail address.';
 return $errorMsg;
 }
 }

 $email = "[email protected]";

 try
 {
 try
 {
 //check for "example" in mail address
 if(strpos($email, "example") !== FALSE)
 {
 //throw exception if email is not valid
 throw new Exception($email);
 }
 }
 catch(Exception $e)
 {
 //re-throw exception
 throw new customException($email);
 }
 }

 catch (customException $e)
 {
 //display custom message
 echo $e->errorMessage();
 }
 ?> 

Example explanation:

The code above detects whether the string "example" is in the email address. If so, throw the exception again:

  1. The customException() class was created as an extension of the old exception class. This inherits all the properties and methods of the old exception class.
  2. Create an errorMessage() function. If the e-mail address is illegal, the function returns an error message.
  3. Set $email variable to a string that is a valid e-mail address but contains the string "example".
  4. The "try" block contains another "try" block so that you can throw the exception again.
  5. Because e-mail contains the string "example," an exception is triggered.
  6. The "catch" block of code catches the exception and throws "customException" again.
  7. Capture "customException" and display an error message.

If the exception is not caught in the current "try" block, it looks for the catch block at a higher level.


Set up the top-level exception processor

set_exception_handler() functions set up user-defined functions to handle all uncosted exceptions.

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

 set_exception_handler('myException');

 throw new Exception('Uncaught Exception occurred');
 ?> 

The output of the above code looks like this:

Exception: Uncaught Exception occurred

In the code above, there is no "catch" block of code, but rather an exception handler that triggers the top level. You should use this function to catch all uncaught exceptions.


The rule for the exception

  • Code that requires exception handling should be placed inside the try block in order to catch potential exceptions.
  • Each try or throw block must have at least one corresponding catch block.
  • Use multiple catch blocks of code to catch different kinds of exceptions.
  • You can throw (throw again) an exception in the catch block within the try block.

In short: if an exception is thrown, it must be caught.

In the next section, we'll take a look at the use of PHP filters.