w1coding.comAll tutorials

PHP Error

PHP lessons
  1. Environment Setup
  2. Introduction
  3. Variables
  4. Basics
  5. Operators
  6. Control
  7. Loops
  8. Variables
  9. Functions
  10. Arrays
  11. Superglobal
  12. File
  13. Loops
  14. Date
  15. Loops
  16. Strings
  17. Error
  18. Class
  19. File
  20. Include
  21. Sessions
  22. Mysql
  23. Cookies
  24. Forms
  25. Cookies
  26. Regular
  27. Authenthication
  28. Fileupload
  29. Mvc
  30. Responsive

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.