PHP Exception Handling

PHP Exception Handling

To deal with errors, PHP 5 came with a new object oriented way for handling errors. It is named as Exception handling that is used to change the normal flow of the code execution if any specified error condition occurs. This condition is called an exception. In this blog, we will explain you about the PHP Exception Handling concept.

 

Following things normally happened if an exception is triggered:

  • The current code state is saved.
  • The code executions will switch into a predefined exception handler function.
  • The handler may then resume the execution from their saved code state, terminate the execution of the script or continue the script from a different location in the code.

To avoid the error, we need to create the code in proper format as given below to handle an exception:

  • try: A function using an exception should be in a “try” block. If exceptions does not trigger, the code will continue as normal. However if the exception triggers, an exception is “thrown”.
  • Throw: This is how you trigger a exception. Each “throw” must have at least one “catch”.
  • Catch: A “catch” block retrieves an exception and creates an object containing the exception information.

Let us take an example,

PHP Exception Handling

After executing the above code, the output generated with a fatal error “Uncaught Exception” message.

Fatal error: Uncaught exception 'Exception' with message 'Value should be 5 or less than 5' in C:\myfolder\test.php:6
Stack trace: #0 C:\myfolder\test.php(12): checkValue(28) #1 {main} thrown in C:\myfolder\test.php on line 6

To handle the above exception, lets try with valid code.

Exception Handling

Above code will generate the below output:

Message: Value must be 1 or below