PHP Exception Handling

PHP Exception Handling : try, throw and catch

The exception is one of powerful mechanism to handle the run-time errors.

An exception is a situation that occurs during the execution of a program.
When exception occurs the normal flow of code is changed if a error condition occurs. This condition is called an exception.

The exception occur in when below situation occurs.

  • User try to open file that can not be found.
  • User enter invalid data.

The Exception are more useful over error handling. We can handle exception using Try, Throw and Catch in PHP.

PHP  Try Block

The try bock contain a block of program code which exception may occur.
A try block always followed by a catch block which handle the exception. If exception not occur then code of program smoothly continue.
Each try must have at least one corresponding catch block. Multiple catch blocks can be used to catch different classes of exceptions.

Syntax of try block

//block of program statement

PHP Catch Block

The catch block must be with a try block. If the exception occurs in try block then the catch block executes. Exceptions can be thrown within a catch block.

Syntax of catch block

//block of program statement
catch ()
//error handling code

PHP Throw Block

Each throw must have at least one catch block. A Throw how you trigger an exception.

Example of Exception Handling in PHP

Above php example we check the number is odd or even, here we input “2” so the result is “The number is even”.

 PHP form Example of Exception Handling

Here, we took same above example with php form like below:

The PHP example out put is :

PHP Exception : Try, catch block Example


Leave a Reply

Your email address will not be published. Required fields are marked *