Error Handling
Error Handling
OUTPUT:
Error: The file does not exist.
Example
• <?php
function division($numerator, $denominator)
{
// perform division operation
echo $numerator / $denominator;
}
// calling the function
division(7, 0);
?>
In such situation, where we know certain condition can lead
to error, we can use conditional statement to handle the
corner case which will lead to error.
Example of Conditional Statement
• <?php
function division($numerator, $denominator)
{
// use if statement to check for zero
if($denominator != 0)
{
echo $numerator / $denominator;
}
else
{
echo "Division by zero(0) no allowed!";
}
}
// calling the function
division(7, 0);
?>
Custom Error Handler
• You can create your own error handler function to deal with the
run-time error generated by PHP engine.
• The custom error handler provides you greater flexibility and
better control over the errors, it can inspect the error and decide
what to do with the error, it might display a message to the user,
log the error in a file or database or send by e-mail, attempt to
fix the problem and carry on, exit the execution of the script or
ignore the error altogether.
• This function must be able to handle a minimum of two
parameters (error level and error message) but can accept up to
five parameters (optionally: file, line-number, and the error
context):
error_function(error_level,error_message,
error_file,error_line,error_context)
Custom Error Handler(contd.)
Parameter Description
error_level Required. Specifies the error report level for the user-defined
error. Must be a value number.
set_error_handler("customError");
Example
• <?php
// custom function to handle error
function abc_error_handler($error_no, $error_msg)
{
echo "Oops! Something unexpected happen...";
echo "Possible reason: " . $error_msg;
echo "We are working on it.";
}
// set the above function s default error handler
set_error_handler(“abc_error_handler");
$result = 7 / 0; //triggers the custom error handler
?>
Set Error Handler(contd.)
<?php
//error handler function
function customError($errno, $errstr)
{
echo "<b>Error:</b> [$errno] $errstr";
}
//trigger error
echo($test);
?>
OUTPUT:
Error: [2] Undefined variable: test
PHP Error Reporting
{
return($dividend / $divisor);
}
}
function customError($errno, $errstr, $errfile, $errline, $errcontext)
{
$message = date("Y-m-d H:i:s - ");
$message .= "Error: [" . $errno ."], " . "$errstr in $errfile on line $errline, ";
$message .= "Variables:" . print_r($errcontext, true) . "\r\n";
error_log($message, 3, "logs/app_errors.log");
die("There was a problem, please try again.");
}
set_error_handler("customError");
echo calcDivision(10, 0);
echo "This will never be printed.";
?>
SendErrorMessagesbyE-Mail
• You can also send e-mail with the error details using the same error_log() function.
<?php
function calcDivision($dividend, $divisor)
{
if ($divisor == 0)
{
trigger_error("calcDivision(): The divisor cannot be zero", E_USER_WARNING);
return false;
}
else
{
return($dividend / $divisor);
}
}
function customError($errno, $errstr, $errfile, $errline, $errcontext)
{
$message = date("Y-m-d H:i:s - ");
$message .= "Error: [" . $errno ."], " . "$errstr in $errfile on line $errline, ";
$message .= "Variables:" . print_r($errcontext, true) . "\r\n";
error_log($message, 1, "[email protected]");
die("There was a problem, please try again. Error report submitted to webmaster.");
}
set_error_handler("customError"); echo calcDivision(10, 0);
echo "This will never be printed.";
?>
Trigger an Error
• In a script where users can input data it is useful to trigger errors when
an illegal input occurs.
<?php
$test=2;
if ($test>=1)
{
trigger_error("Value must be 1 or below");
}
?>
OUTPUT:
Notice: Value must be 1 or below in C:\xampp\htdocs\trigger.php on line
4
Trigger an Error contd.
• Consider the following function that calculates division of the
two numbers.
• <?php
function calcDivision($dividend, $divisor)
{
return($dividend / $divisor);
}
// Calling the function
echo calcDivision(10, 0);
?>
If a value of zero (0) is passed as the $divisor parameter, the
error generated by the PHP engine will look something like this:
Warning: Division by zero in C:\wamp\www\project\test.php on
line 3
Trigger an Error contd.
• Consider the following example that uses the trigger_error() function to generate the
error.
• <?php
function calcDivision($dividend, $divisor)
{
if($divisor == 0)
{
trigger_error("The divisor cannot be zero", E_USER_WARNING);
return false;
}
else
{
return($dividend / $divisor);
}
}
// Calling the function
echo calcDivision(10, 0);
?>
Warning: The divisor cannot be zero in C:\wamp\www\project\error.php on line 4
Trigger an Error(contd.)
• An error can be triggered anywhere you wish in a script, and by
adding a second parameter, you can specify what error level is
triggered.
• Throw
• It is a keyword that is used to throw an exception. It also
helps to list all the exceptions that a function throws but
does not handle itself. Remember that each throw must
have at least one "catch".
• Finally
• The final block contains a code, which is used for clean-
up activity in PHP. It executes the essential code of the
program.
Example of exception handling in PHP
• <?php
try
{
$firstValue = 10;
$secondValue = 0;
• Output
Exception: Divide by Zero exception occurred
Task
1.You are building a simple calculator that takes two
numbers and a mathematical operation (add, subtract,
multiply, divide) from a form submission.
• The calculator should handle division by zero gracefully
by throwing an exception with the message "Division by
zero is not allowed."
• If the user inputs a non-numeric value, an exception
should be thrown with the message "Invalid input. Please
enter valid numbers."
• Write a PHP script that processes the input and handles
errors using exception handling. If no errors occur, display
the result of the calculation.
Task
2.You are developing a user registration form where users must fill
out fields like username, password, and email. Your script should:
• Validate that the username is at least 5 characters long. If not,
throw an exception with the message "Username must be at least 5
characters."
• Validate that the email contains a valid format. If not, throw an
exception with the message "Invalid email format."
• Validate that the password contains at least 8 characters, and if
not, throw an exception with the message "Password must be at
least 8 characters."
• Handle any errors by displaying the appropriate error message to
the user.
• Write a PHP script to handle the form submission, validate user
inputs, and ensure proper error handling with meaningful error
messages
• Here is an example of exception handling technique. The
code renders two text fields on the browser and asks the
user to enter two numbers for their division to be
performed. If the second number (denominator) is 0, an
exception is thrown and the program enters the catch
block and prints the exception message. Otherwise the
result of division is displayed.