Error handling in PHP- Tutorialpath

PHP is used for web development. Error handling in PHP is almost similar to error handling in all programming languages. The default error handling in PHP will give file name line number and error type.

Ways to handle PHP Errors:

  • Using die() method
  • Custom Error Handling

Basic error handling: Using die() function The die() function print a message and exit from current script.

Syntax:

Example:

 

Output:

What is an Exception?

An error is an unexpected program result that cannot be handled by the program itself.

Errors are resolved by fixing the program. An example of an error would be an infinite loop that never stops executing.

An exception is unexpected program result that can be handled by the program itself.

Examples of exception include trying to open a file that does not exist.

This exception can be handled by either creating the file or presenting the user with an option of searching for the file.

Errors vs. Exceptions

Many use error handling and exception handling interchangeably.  When we say error handling we are referring to the process of catching errors produced by your program which needs proper action. Since PHP came into a new object-oriented (OOP) way of dealing with errors, exception handling was introduced. It is used to change the usual way of handling code execution of a specific error condition when it occurs. In this way, exception handling provides a better technique over error handling.

How does exception handling in PHP  work?

Just like any other object-oriented programming, PHP also uses the following keywords related to exceptions:

Try:  this means that if the exception does not trigger, the code will just execute normally but if the exception triggers then it will call “thrown” exception

Throw: every time an exception has been triggered, a “throw” exception must be paired with at least one “catch”

Catch:  this block of code should retrieve an exception and create an object including the exception information.

 

Leave a Reply

Your email address will not be published.