0% found this document useful (0 votes)
35 views

Error Handling

Uploaded by

BAKAMO
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views

Error Handling

Uploaded by

BAKAMO
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 30

ERROR HANDLING

PHP Error Handling

• An Error is said to have occurred when a piece of code


returns unexpected result or stops abruptly due to some
incorrect code for example division by zero, or infinite
loop etc.
• In PHP, we can set PHP configurations to show error
messages in the browser or hide them.
• PHP provides multiple ways to handle errors,
1.Handling error in code using conditional statements
or die() function
2.Using Custom Error Handlers
3.PHP error reporting
Handling Errors

• Sometimes your application will not run as it supposed to do,


resulting in an error. There are a number of reasons that may
cause errors, for example:
• The Web server might run out of disk space
• A user might have entered an invalid value in a form field
• The file or database record that you were trying to access
may not exist
• The application might not have permission to write to a file on
the disk
• A service that the application needs to access might be
temporarily unavailable
• These types of errors are known as runtime errors, because
they occur at the time the script runs. They are distinct from
syntax errors that need to be fixed before the script will run.
Understanding Error Levels

• Usually, when there's a problem that prevents a script from


running properly, the PHP engine triggers an error. Each error is
represented by an integer value and an associated constant. The
following table list some of the common error levels:
• E_ERROR-Display syntax error.
• E_WARNING-Only displays warning messages and doesn't stop
the execution of the script.
• E_NOTICE-Displays notice that occur during normal code
execution.
• E_USER_ERROR-Display user generated errors i.e the custom
error handlers.
• E_USER_WARNING-Display user generated warning messages.
• E_USER_NOTICE-Display user generated notices.
• E_ALL-Display all errors and warnings.
die() function
• The die() is an inbuilt function in PHP.
• It is used to print message and exit from the current php
script. It is equivalent to exit() function in PHP.
Basic Error Handling Using the die() Function

• Consider the following example that simply tries to open a


text file for reading only.
• <?php
// Try to open a non-existent file
$file = fopen("sample.txt", "r");
?>
If the file does not exist you might get an error like this:
Warning: fopen(sample.txt) [function.fopen]: failed to open
stream: No such file or directory in C:\wamp\www\project\
test.php on line 2
die() function(contd.)
<?php
if(file_exists("mytestfile.txt"))
{
$file = fopen("mytestfile.txt", "r");
}
else
{
die("Error: The file does not exist.");
}
?>

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.

error_messag Required. Specifies the error message for the user-defined


e error
error_file Optional. Specifies the filename in which the error occurred
error_line Optional. Specifies the line number in which the error occurred
error_context Optional. Specifies an array containing every variable, and their
values, in use when the error occurred
Set Error Handler
• The default error handler for PHP is the built in error
handler.
• In PHP, we can use our custom method to display any
message or execute any code when error occurs. All we
have to do is set our method as the default error
handler for PHP using the function set_error_handler()

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";
}

//set error handler


set_error_handler("customError");

//trigger error
echo($test);
?>

OUTPUT:
Error: [2] Undefined variable: test
PHP Error Reporting

• We can use PHP function error_reporting() to set which


errors to show and which errors to hide.
• Following is the syntax for this function:
• <?php
// error reporting function
error_reporting($reporting_level);
?>
• The value for the variable $reporting_level defines which
error to show and which errors to hide, if we do not
provide any value for it, the error reporting will be set
to default.
Error Logging

• Log Error Messages in a Text File


<?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, 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.

• This is done by the trigger_error() function.

<?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.

• Possible error types:

• E_USER_ERROR - Fatal user-generated run-time error. Errors


that can not be recovered from. Execution of the script is halted
• E_USER_WARNING - Non-fatal user-generated run-time
warning. Execution of the script is not halted
• E_USER_NOTICE - Default. User-generated run-time notice.
The script found something that might be an error, but could
also happen when running a script normally
Exceptions Handling

• In PHP, exception handling is a powerful way which can


handle runtime errors. So runtime errors are also known
as exceptions.
• It's a signal which indicates some errors may occur due to
various reasons such as database connection failing, the
file doesn't exist, etc. So the main purpose of using
exception handling is to maintain the normal execution of
the application.
• As an exception interrupts the normal flow of the
application. But it is different from an error because an
exception can be handled, whereas an error cannot be
handled by the program itself.
Benefits of Exception Handling

• Exception handling can control run-time errors that occur


in the program.
• It can avoid abnormal termination of the program and also
shows the behavior of the program to users.
• It can separate the error handling code and normal code
by using try-catch block.
• PHP offers the following keywords for handling
exceptions:
• Try
• The try block contains the code that may have an
exception or where an exception can occur. When an
exception occurs inside the try block during the runtime of
the program, it is caught and resolved in the catch block.
The try block must be followed by a catch or finally block.
A try block can be followed by nested catch blocks.
• Catch
• The catch block contains the code that executes when a
particular exception is thrown. It is always used with a try
block, not alone. When an exception occurs, PHP finds
the matching catch block.

• 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;

if ($secondValue == 0) throw new Exception("Divide by Zero exception occurred");


$result = $firstValue / $secondValue;
print("Result is : ", $result);
}
catch(Exception $e)
{
print("Exception: %s", $e->getMessage());
}
?>

• 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.

You might also like