Error & Exception Handling PHP is the process of figuring out what went wrong with your programme and fixing it. If you don\’t deal with errors the right way, it could lead to a lot of unexpected things.
Handling errors in PHP is very easy.
Using the function die()
Before going any further with your PHP programme, you should check for all possible error conditions and take the right steps when they happen.
Try the following example with and without the /tmp/dummy.txt file.
<?php
if(!file_exists(\”/tmp/dummy.txt\”)) {
die(\”404 File not found\”);
}else {
$file = fopen(\”/tmp/dummy.txt\”,\”r\”);
print \”File Opend sucessfully\”;
}
// Test code here.
?>
So, you can write code that works well. Using the above method, you can stop your programme when it makes a mistake and show a more helpful error message.
Custom Error Handling Function Definition
You can make your own error-handling function. PHP gives you a framework for defining how to handle errors.
This function must be able to handle at least two parameters (error level and error message), but it can take up to five (optionally: file, line-number, and the error context).
Syntax
error function(error level,error message, error file,error line,error context);
error level
Required: Sets the error report level for the user-defined error. Must be a number value.
error_message
Required: Gives the error message for the user-defined error.
error_file
Optional: Gives the name of the file in which the error happened.
error_line
Optional—Lists the line number where the error happened.
error_context
Optional: Gives a list of all the variables and their values that were being used when the error happened.
Possible Error levels
The user-defined error handler can be used for each of these different types of errors. Using the | operator, these values can be used together.
.E_ERROR
Fatal run-time errors. The script is no longer being run.
E_WARNING
Non-fatal run-time errors. The script is not stopped from running.
E PARSE
Compile-time parse errors. Only the parser should be able to make parse errors.
E_NOTICE
Run-time notices. Something that might be an error, but could also happen when a script is run normally, was found by the script.
E_CORE_ERROR
Fatal errors that happen when PHP starts up for the first time.
E_CORE_WARNING
Non-fatal run-time errors. This happens when PHP starts up for the first time.
E_USER_ERROR
Fatal user-generated error. This is like when a programmer uses the PHP function trigger error to set an E ERROR ()
E_USER_WARNING
User-made warning that is not fatal. This is like when a programmer uses the PHP function trigger error to set an E WARNING ()
E_USER_NOTICE
Notice made by the user. This is like when a programmer uses the PHP function trigger error to set an E NOTICE ()
E_STRICT
Run-time notices. Allow PHP to suggest changes to your code that will make it work best with other programmes and work in the future.
E_RECOVERABLE_ERROR
Catchable fatal error. This is the same as an E ERROR, but a user-defined handle can catch it (see also set error handler()).
E_ALL
All errors and warnings except level E STRICT (E STRICT will be part of E ALL starting with PHP 6.0).
All of the above error levels can be set using the following PHP built-in library function, where level can be any of the values listed in the table above.
int error reporting ([int $level])
Here\’s how you can make one error-handling function:
<?php
function handleError($errno, $errstr,$error_file,$error_line) {
echo \”<b>Error:</b> [$errno] $errstr – $error_file:$error_line\”;
echo \”<br />\”;
echo \”Terminating PHP Script\”;die();
}
?>
Exceptions Handling
Like other programming languages, PHP 5 has an exception model. Exceptions are important because they give you more control over how you handle errors.
Let\’s talk about their new keyword, which has to do with exceptions.
Try: A \”try\” block should be around a function that throws an exception. If the exception doesn\’t happen, the code will keep going like usual. If the exception does happen, however, an exception is \”thrown.\”
Throw: This is how you make an exception happen. There must be at least one \”catch\” for every \”throw.\”
Catch: A \”catch\” block gets an exception and makes an object with the information about the exception.
When an exception is thrown, the code that comes after the statement is not run. Instead, PHP tries to find the first catch block that matches. If an exception isn\’t caught, PHP will give a Fatal Error with the message \”Uncaught Exception…
- In PHP, you can throw and catch (or \”catch\”) an exception. Code can be put in a try block.
- Each try must have at least one catch block, and different types of exceptions can be caught in different catch blocks.
- In a catch block, exceptions can be thrown (or re-thrown).
Example
<?php
try {
$error = \’Always throw this error\’;
throw new Exception($error);// Code following an exception is not executed.
echo \’Never executed\’;
}catch (Exception $e) {
echo \’Caught exception: \’, $e->getMessage(), \”\\n\”;
}// Continue execution
echo \’Test Error\’;
?>
In the example above, the $e->getMessage function is used to get the error message. The Exception class also has the following functions that can be used.
- getMessage() = error message
- getCode() = exception code
- getFile() − source filename
- getLine() − source line
- getTrace() gives you an array of n backtraces ()
- getTraceAsString() returns a string of formatted trace
Making a custom handler for exceptions
You can set up your own user-defined exception handler function by calling the following function.
string set_exception_handler ($exception handler is a callback)
This is the name of the function that will be called when an uncaught exception happens. This function must be defined before set_exception_handler
<?php
function exception_handler($exception) {
echo \”Uncaught exception: \” , $exception->getMessage(), \”\\n\”;
}set_exception_handler(\’exception_handler\’);
throw new Exception(\’Uncaught Exception\’);echo \”Not Executed\”;
?>