We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2
Ch -5 error handling
Examples
1. Using set_error_handler() for Custom Error Handling
Create a PHP file
<?php
// Custom error handler function
function customErrorHandler($errno, $errstr, $errfile, $errline) { // Check if the error is not a notice or if it's an error that needs to be reported if (!(error_reporting() & $errno)) { return; }
// Display error details
echo "Error [$errno]: $errstr in $errfile on line $errline<br>";
// Log the error to a file (optional)
error_log("Error [$errno]: $errstr in $errfile on line $errline", 3, 'errors.log'); }
// Set the custom error handler
set_error_handler('customErrorHandler');
// Trigger different types of errors
echo $undefinedVariable; // Notice: Use of an undefined variable trigger_error("This is a custom warning message.", E_USER_WARNING); // Custom warning trigger_error("This is a custom error message.", E_USER_ERROR); // Custom error
// Check the error log file 'errors.log' in the same directory for logged errors
2. Try catch for exception handling
<?php
// Function that demonstrates exception handling
function divideNumbers($numerator, $denominator) { try { if ($denominator == 0) { throw new Exception("Division by zero is not allowed."); } $result = $numerator / $denominator; return $result; } catch (Exception $e) { // Handle the exception by displaying the error message return "An error occurred: " . $e->getMessage(); } }
// Test the function with different values
echo "Result of division: " . divideNumbers(10, 2) . "<br>"; // This should succeed echo "Result of division: " . divideNumbers(10, 0) . "<br>"; // This should trigger the exception ?>