PHP Error Handling

Error Handling in any programming language is the process to catch the errors in the program and return the appropriate message based on some conditions. And if you will not handle the errors your program will always break and will see some auto generated errors returned by the programming language and in the chapter you will learn PHP Error Handling.

PHP Error Handling

Error Handling in PHP is quite easy. So we will show you error handling with some examples.

Error Handling with die(); function

You can use die(); function for any simple error handling process as you can see in the following example:

Example

In the above example, the program will return a proper message in both the cases and program will not break anywhere.

Custom Error Handling in PHP

We can create a function to handle the errors and we can call that function whenever required.

Syntax

As you can see, we can pass up to five parameters in the function but two parameters are compulsory.

The compulsory parameters are “error_level” and “error_message”.

And the optional parameters are “error_file”, “error_line”, and “error_context”.

The complete description of all the parameters are given below:

Parameters  Description
error_level This is a required parameter which defines the error level and this must be a value number.
error_message This is a required parameter which defines the error message.
error_file This is an optional parameter which defines the file name in which the error occurred.
error_line This is an optional parameter which defines the line number in which the error occurred.
error_context This is an optional parameter which defines an array containing every variable and their values in use when the error occurred.

 

Leave a Reply

Your email address will not be published.