error

PHP Error Handling

PHP Error Handling

Error handling is an essential part of writing secure and user-friendly PHP applications. PHP has built-in functions for handling errors and exceptions.

Basic Error Handling

To handle errors in PHP, you can use the try-catch block:

      
        <?php
          try {
            // Code that may cause an error
            $num = 10 / 0; // Division by zero
          } catch (Exception $e) {
            echo "Error: " . $e->getMessage(); // Catch the exception and display message
          }
        ?>
      
    

Custom Error Handler

You can also set a custom error handler using set_error_handler():

      
        <?php
          function customError($errno, $errstr) {
            echo "Error [$errno]: $errstr";
          }

          set_error_handler("customError");

          echo $undefined_variable; // Triggers the custom error handler
        ?>
      
    

Activity

Try It Yourself!

Create a script that handles a division by zero error and displays a custom message.

Quiz

Quick Quiz

  1. How do you handle exceptions in PHP?
  2. What is the function used to set a custom error handler?

Answers: Use the try-catch block to handle exceptions. Use set_error_handler() to set a custom error handler.