PHP - Error Handling

Error handling is the process of catching errors raised by your program and then taking appropriate action. If you would handle errors properly then it may lead to many unforeseen consequences.

Using die() function

While writing your PHP program you should check all possible error condition before going ahead and take appropriate action when required.

Example -

This way you can write an efficient code. Using above technique you can stop your program whenever it errors out and display more meaningful and user friendly message.

Defining Custom Error Handling Function

You can write your own function to handling any error. PHP provides you a framework to define error handling function. 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) −

Possible Error levels

These error report levels are the different types of error the user-defined error handler can be used for. These values cab used in combination using | operator

Example -

Once you define your custom error handler you need to set it using PHP built-in library set_error_handler function. Now lets examine our example by calling a function which does not exist.

Example -