Error handling can be described as a process of catching errors raised by your program and taking appropriate actions.
It is very easy in PHP to handle errors.
Handling Errors using the die() Function
Example
<?php if(!file_exists("/tmp/test.txt")) { die("File not found"); }else { $file = fopen("/tmp/test.txt","r"); print "Opend file sucessfully"; } // Test of the code here. ?>
Defining Custom Error Handling Function
This PHP function must be able to handle at least 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) -
Syntax
error_function(error_level,error_message, error_file,error_line,error_context);
Sr.No | Parameter & Description |
---|---|
1 | error_level Required - Specifies the error report level for the user-defined error. Must be a value number. |
2 | error_message Required - Specifies the error message for the user-defined error |
3 | error_file Optional - Specifies the file name in which the error occurred |
4 | error_line Optional - Specifies the line number in which the error occurred |
5 | error_context Optional - Specifies an array containing every variable and their values in use when the error occurred |
Possible Error Levels
Sr.No | Constant & Description | Value |
---|---|---|
1 | .E_ERROR Fatal run-time errors. Execution of the script is halted | 1 |
2 | E_WARNING Non-fatal run-time errors. Execution of the script is not halted | 2 |
3 | E_PARSE Compile-time parse errors. Parse errors should only be generated by the parser. | 4 |
4 | E_NOTICE Run-time notices. The script found something that might be an error, but could also happen when running a script normally | 8 |
5 | E_CORE_ERROR Fatal errors that occur during PHP's initial start-up. | 16 |
6 | E_CORE_WARNING Non-fatal run-time errors. This occurs during PHP's initial start-up. | 32 |
7 | E_USER_ERROR Fatal user-generated error. This is like an E_ERROR set by the programmer using the PHP function trigger_error() | 256 |
8 | E_USER_WARNING Non-fatal user-generated warning. This is like an E_WARNING set by the programmer using the PHP function trigger_error() | 512 |
9 | E_USER_NOTICE User-generated notice. This is like an E_NOTICE set by the programmer using the PHP function trigger_error() | 1024 |
10 | E_STRICT Run-time notices. Enable to have PHP suggest changes to your code which will ensure the best interoperability and forward compatibility of your code. | 2048 |
11 | E_RECOVERABLE_ERROR Catchable fatal error. This is like an E_ERROR but can be caught by a user defined handle (see also set_error_handler()) | 4096 |
12 | E_ALL All errors and warnings, except level E_STRICT (E_STRICT will be part of E_ALL as of PHP 6.0) | 8191 |
int error_reporting ( [int $level] )
Example
<?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(); } ?>
<?php error_reporting( E_ERROR ); 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(); } //set error handler set_error_handler("handleError"); //trigger error myFunction(); ?>
Exception Handling in PHP
Let us explain some of the new keywords related to exceptions -
- Try - A function that is using an exception should be in a "try" block. If the exception does not trigger, the code is going to continue as usual. But if the exception triggers, an exception is "thrown".
- Throw - This is the way that an exception is triggered. A "throw" must have a least a "catch".
- Catch - A "catch" retrieves an exception and creates an object holding the exception information.
- An exception can be thrown and caught within PHP. The code may be surrounded in a try block.
- Each try block must have at least a corresponding catch. Multiple catch blocks can be used for catching different classes of exceptions.
- Exceptions can be thrown or re-thrown in a catch block.
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 'Hello World'; ?>
- getMessage() - Used to get the exception message.
- getCode() - Used for getting code of the exception.
- getFile() - Source filename.
- getLine() - Source line.
- getTrace - Used to get the n array of the backtrace().
- getTraceAsString - Used for getting the formatted string of trace.
Creating a Custom Exception Handler
string set_exception_handler ( callback $exception_handler )
Example
<?php function exception_handler($exception) { echo "Uncaught exception: " , $exception->getMessage(), "\n"; } set_exception_handler('exception_handler'); throw new Exception('Uncaught Exception'); echo "Not Executed\n"; ?>
Feel free to ask your questions where necessary and we will attend to them as soon as possible. If this tutorial was helpful to you, you can use the share button to share this tutorial.
Follow us on our various social media platforms to stay updated with our latest tutorials. You can also subscribe to our newsletter in order to get our tutorials delivered directly to your emails.
Thanks for reading and bye for now.