PHP Try Catch Example: Exception & Error Handling Tutorial
⚡ Smart Summary
Error Handling and Exceptions in PHP keep applications stable and secure by managing unexpected conditions instead of exposing raw errors. This walkthrough explains errors versus exceptions, die statements, custom error handlers, error reporting levels, and the try, throw, and catch exception model with multiple exception types.
What is an Exception?
An error is an unexpected program result that cannot be handled by the program itself.
Errors are resolved by fixing the program. An example of an error would be an infinite loop that never stops executing.
An exception is an unexpected program result that can be handled by the program itself.
Examples of an exception include trying to open a file that does not exist.
This exception can be handled by either creating the file or presenting the user with an option of searching for the file.
Why handle exceptions?
- Avoid unexpected results on our pages, which can be very annoying or irritating to our end users
- Improve the security of our applications by not exposing information which malicious users may use to attack our applications
- PHP exceptions are used to change the normal flow of a program if any predictable error occurs.
PHP Error handling
When an error occurs, depending on your configuration settings, PHP displays the error message in the web browser with information relating to the error that occurred.
PHP offers a number of ways to handle errors. We are going to look at three commonly used methods:
- Die statements – the die function combines the echo and exit functions in one. It is very useful when we want to output a message and stop the script execution when an error occurs.
- Custom error handlers – these are user defined functions that are called whenever an error occurs.
- PHP error reporting – the error message depends on your PHP error reporting settings. This method is very useful in a development environment when you have no idea what caused the error. The information displayed can help you debug your application.
Error handling examples
Let us now look at some simple examples with error handling routines.
Let us suppose that we have a calculation that could divide a number by zero. We want to handle that case cleanly instead of letting PHP show a raw error.
The code below implements the above example.
<?php
$denominator = 0;
echo 2 / $denominator;
?>
Assuming you saved the file simple_error.php in the phptuts folder, open the URL http://localhost/phptuts/simple_error.php
You will get the following results.
As you can see from the above results, it makes our application look unprofessional and can be annoying to the user.
We will modify the above code and write an error handler for the application.
<?php $denominator = 0; if ($denominator != 0) { echo 2 / $denominator; } else { echo "cannot divide by zero (0)"; } ?>
Assuming you saved the above code as error_handling.php, open the URL http://localhost/phptuts/error_handling.php
Note: it is a good security practice to display a message like the one shown above instead of showing a raw message like “File not found”.
Let us look at another example that uses a custom error handler.
The custom error handler will be set as the default PHP error handling function and will basically display an error number and message.
The code below illustrates the implementation of the above example.
<?php function my_error_handler($error_no, $error_msg) { echo "Oops, something went wrong:"; echo "Error number: [$error_no]"; echo "Error Description: [$error_msg]"; } set_error_handler("my_error_handler"); echo (5 / 0); ?>
Open the URL http://localhost/phptuts/custom_error_handler.php. You will get the following results.
As you can see from the above example, custom error handlers are powerful in the sense that:
- They allow us to customize the error messages.
- The custom error handler can also include error logging in a file or database, emailing the developer, and similar actions.
Let us now look at the third type of error handling. We will be using the PHP built-in error_reporting function. It has the following basic syntax.
<?php error_reporting($reporting_level); ?>
HERE,
- “error_reporting” is the PHP error reporting function
- “$reporting_level” is optional and can be used to set the reporting level. If no reporting level has been specified, PHP will use the default error reporting level as specified in the php.ini file.
| Reporting Level | Description | Example |
|---|---|---|
| E_WARNING | Displays warning messages only. Does not halt the execution of the script | error_reporting(E_WARNING); |
| E_NOTICE | Displays notices that can occur during normal execution of a program or could be an error. | error_reporting(E_NOTICE); |
| E_USER_ERROR | Displays user generated errors, i.e. a custom error handler | error_reporting(E_USER_ERROR); |
| E_USER_WARNING | Displays user generated warning messages | error_reporting(E_USER_WARNING); |
| E_USER_NOTICE | Displays user generated notices | error_reporting(E_USER_NOTICE); |
| E_RECOVERABLE_ERROR | Displays errors that are not fatal and can be handled using custom error handlers | error_reporting(E_RECOVERABLE_ERROR); |
| E_ALL | Displays all errors and warnings | error_reporting(E_ALL); |
Difference between Errors and Exception
- Exceptions are thrown and intended to be caught, while errors are generally irrecoverable.
- Exceptions are handled in an object oriented way. This means that when an exception is thrown, an exception object is created that contains the exception details.
The table below shows the exception object methods.
| Method | Description | Example |
|---|---|---|
| getMessage() | Displays the exception’s message |
<?php
echo $e->getMessage();
?>
|
| getCode() | Displays the numeric code that represents the exception |
<?php
echo $e->getCode();
?>
|
| getFile() | Displays the file name and path where the exception occurred |
<?php
echo $e->getFile();
?>
|
| getLine() | Displays the line number where the exception occurred |
<?php
echo $e->getLine();
?>
|
| getTrace() | Displays an array of the backtrace before the exception |
<?php print_r( $e->getTrace()); ?> |
| getPrevious() | Displays the previous exception before the current one |
<?php
echo $e->getPrevious();
?>
|
| getTraceAsString() | Displays the backtrace of the exception as a string instead of an array |
<?php
echo $e->getTraceAsString();
?>
|
| __toString() | Displays the entire exception as a string |
<?php
echo $e->__toString();
?>
|
Below is the basic syntax for throwing an exception.
<?php throw new Exception("This is an exception example"); ?>
HERE,
- “throw” is the keyword used to throw the exception
- “new Exception(…)” creates an exception object and passes the “This is an exception example” string as the message parameter.
The above code outputs the following message.
We are now going to look at an example that implements the throw and catch exceptions. We will modify the above example and include try, throw, and catch.
It has the following basic syntax.
<?php try { // code goes here that could potentially throw an exception } catch (Exception $e) { // exception handling code goes here } ?>
HERE,
- “try{…}” is the block of code to be executed that could potentially raise an exception
- “catch(Exception $e){…}” is the block of code that catches the thrown exception and assigns the exception object to the variable $e.
The code below shows the basic exception example with try, throw, and catch implemented. The program deliberately throws an exception which it then catches.
<?php try { $var_msg = "This is an exception example"; throw new Exception($var_msg); } catch (Exception $e) { echo "Message: " . $e->getMessage(); echo ""; echo "getCode(): " . $e->getCode(); echo ""; echo "__toString(): " . $e->__toString(); } ?>
Open the URL http://localhost/phptuts/exception_handling.php. You will get the following results.
It is also possible to create multiple exceptions for one PHP try statement depending on the type of exception thrown.
See the article on MySQL, PHP data access for implementation examples of multiple exceptions.
Multiple Exceptions
Multiple exceptions use multiple catch blocks to handle the thrown exceptions. Multiple exceptions are useful when:
- You want to display a customized message depending on the exception thrown
- You want to perform a unique operation depending on the exception thrown
The flowchart below illustrates how multiple exceptions work.
Let us look at an example that uses multiple exceptions. We will modify the code that divides a number by the passed in denominator.
We expect two types of exceptions to occur:
- Division by zero
- Division by a negative number
For simplicity’s sake, we will only display the exception type in our catch blocks. The PHP built-in Exception class is used to throw exceptions. We will create two classes that extend the Exception class and use them to throw exceptions.
The code below shows the implementation.
<?php class DivideByZeroException extends Exception {}; class DivideByNegativeException extends Exception {}; function process($denominator) { try { if ($denominator == 0) { throw new DivideByZeroException(); } else if ($denominator < 0) { throw new DivideByNegativeException(); } else { echo 25 / $denominator; } } catch (DivideByZeroException $ex) { echo "DIVIDE BY ZERO EXCEPTION!"; } catch (DivideByNegativeException $ex) { echo "DIVIDE BY NEGATIVE NUMBER EXCEPTION!"; } catch (Exception $x) { echo "UNKNOWN EXCEPTION!"; } } process(0); ?>
Testing the code
We will assume you saved multiple_exceptions.php in the phptuts folder.
Browse to the URL http://localhost/phptuts/multiple_exceptions.php
Switch back to the PHP file and pass -1 as the parameter as shown in the following diagram.
Browse to the URL http://localhost/phptuts/multiple_exceptions.php. What results do you get? Now pass 3 as the parameter. What results do you get?
The finally Block and PHP 7 Error Model
Modern PHP adds two important pieces to the model above. The finally block runs after try and catch regardless of whether an exception was thrown, which makes it ideal for cleanup such as closing a file or a database connection.
Since PHP 7, many former fatal errors are thrown as Error objects. Both Exception and Error implement the Throwable interface, so a catch (\Throwable $e) block can handle either one.
<?php try { $result = 10 / 0; } catch (DivisionByZeroError $e) { echo "Caught: " . $e->getMessage(); } finally { echo "This message always runs"; } ?>
Here, dividing by zero throws a DivisionByZeroError in PHP 8, the catch block reports it, and the finally block always runs, printing its message whether or not an error occurred.









