PHP Try and Catch Tutorial with Example

Errors are something which may occur anytime with in the php script. As a web developer I tried my best to write error free code. But error is something you cannot overcome.

PHP has built in error handling mechanism that will trigger on specific type. A list of these types are available on php site.
PHP also provide try and catch block to handle errors more sophistically. So in this tutorial I will discuss try and catch block with example.

Try and Catch Syntax:

Try block attempt to execute some code and if the code has error then try block raise an exception.

Catch block then catch the exception and assign that exception object to $e.

Exception object has following method.

Method Description
getMessage() Get exception message
getCode() Get the numeric exception code
getFile() Gets the file in which the exception was created
getLine() Get the line number where the exception occurred
getTrace() Get the backtrace before the exception
getPrevious() Displays the previous exception
getTraceAsString() Get the backtrace of the exception as a string instead of an array
__toString() String representation of the exception

Try and Catch Basic Example:

Below is the simple example in which we have 2 variable $a and $b. In try block there is a $c variable that holds quotient of $a / $b.
If $c (quotient) is greater than 1 then it will throw an error. Right now $a has 10 value and $b has 9 value. So below code will throw an error. If you change $b value greater than or equal to 10 then it will print else block which is “Quotient is here”. But right now it will throw an error.

Try and Catch Multiple Exception Example:

You can also create different exception for different errors. You just need to create other class that extends Exception class. Below is the multiple try and catch exception example using previous example. But this time I will add different exception for different error.
If $c (quotient) is greater than 1 then I will throw greaterThanException and if $c is less than 1 then I will throw lessThanException and if $c equal to 1 then I will print “Here is quotient” message.


Posted in PHP

Leave a Reply

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