PHP Error Handling using Try Catch Tutorial

In this tutorial, you will learn how to Handle Errors in PHP Scripts using the Try Catch. The tutorial's main purpose is to provide IT/CS students or self-learners with a reference to enhance their knowledge for handling the possible errors that may occur on their PHP Scripts. Here, I will be providing a straightforward script that demonstrates Error Handling using Try Catch. A sample source code zip file is also provided and is free to download.

What is Error Handling?

Error Handling is a response and recovery method from error circumstances that are presented in a software application or web application. It can help to maintain the normal flow of executing the application whereas the error-handling anticipates, detects, and provide resolution for any errors that may occur while running the particular program script.

How can we Implement Error Handling in PHP?

PHP version 5 up to the latest version comes with an object-oriented way called Exceptions to capture and deal with errors. This can be used for changing the normal flow or executing the code or scripts when an error condition occurs. Using the Try Catch statement, we can handle the error better. This statement allows us to try a block of code and catch the exception if the script fails. In a web application, using the Try Catch statement and the PHP's Exception Handling is the best way to handle the error without breaking the execution of your page's script on the user or client side.

Example #1

Here's a sample snippet that demonstrates the error handling using PHP Exception and Try Catch statement.

  1. <?php
  2. try{
  3. // Comment the following variable so error will occur
  4. $sampleVar = "lorem ipsum";
  5. // or Uncomment the following
  6. throw new ErrorException("Opps. The <b>\$sampleVar</b> is unrecognize or not set", 101);
  7. ?>
  8. <div class="alert alert-primary mb-3 rounded-0">
  9. There's no error occured. <br>
  10. Sample Variabale is: <b><?= $sampleVar ?></b>
  11. </div>
  12. <?php
  13. } catch (Exception $e){
  14. ?>
  15. <div class="alert alert-danger mb-3 rounded-0">
  16. <div>There's an error occured.</div>
  17. <h5 class="fw-bolder">Message:</h5>
  18. <div class="ps-3">
  19. <?= $e->getMessage(); ?>
  20. </div>
  21. </div>
  22. <?php
  23. } finally {
  24. ?>
  25. <div class="alert alert-info mb-3 rounded-0">
  26. This message will always show even an error occurred or not.
  27. </div>
  28. <?php
  29. }
  30. ?>

The sample snippet above represents handling the execution of a simple script that is echoing or displaying the text content of a variable. On the Try block, a specific variable will be shown in a simple alert component. When the specified variable is not set or unknown PHP will stop the execution and return with an error or you can also create a custom exception for the specific error that occurred to give details about the problem on the front end (check out the comments in a try block to test it). If an exception has been captured or when the error occurred, the catch block will handle the exception and return the error message with a custom interface. The finally block contains the script or line of codes you wanted to execute whether an exception has been captured or not.

For the sample snippet given above, commenting out the line of code with ErrorException on the try block will output something like the image below:

PHP Error Handling using Try Catch

And the finally block will output like the image below even if no error occurred:

PHP Error Handling using Try Catch

Example #2

The snippet below demonstrates the usage of error handling for database connection with MySQL in PHP:

  1. <?php
  2. try{
  3. $conn = new mysqli("localhost", "root", "", "unknown_db");
  4. if(!$conn){
  5. throw new ErrorException($conn->error, $conn->errno);
  6. }else{
  7. echo "<div class='alert alert-success mb-3 rounded-0'>Database Connection is successful.</div>";
  8. $conn->close();
  9. }
  10. } catch (Exception $e) {
  11. echo "<div class='alert alert-danger mb-3 rounded-0'>".($e->getMessage())."</div>";
  12. }
  13. ?>

As default, if the error reporting is on in your web application. Failure of database connection with MySQL will return an error due to some reasons and will cause to break the execution of the whole program. But with the proper handling of the error, we can still execute the script that we want to run and those scripts that are not linked or related to the database connection.

For example, the MySQL service is not running or not active on the server. The snippet provided will possibly output like the image below:

PHP Error Handling using Try Catch

And if the MySQL Service is active but the database name provided does not exist. The script will possibly return the following:

PHP Error Handling using Try Catch


I have provided a source code zip file of a simple PHP Program that demonstrates Error Handling using Try Catch on this website and is free to download. You can download the file by clicking the download button located below this tutorial's content.

Here's the snapshot of the sample application interface:

PHP Error Handling using Try Catch

That's the end of this tutorial. I hope this PHP Error Handling using Try Catch Tutorial will help you with what you are looking for and will be useful for current and future PHP Projects.

Explore more on this website for more Tutorials and Free Source Codes.

Happy Coding =)

Add new comment