Error handling is an essential part of writing secure and user-friendly PHP applications. PHP has built-in functions for handling errors and exceptions.
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
}
?>
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
?>
Create a script that handles a division by zero error and displays a custom message.
Answers: Use the try-catch
block to handle exceptions. Use set_error_handler()
to set a custom error handler.