Skip to main content

PHP Try Catch to Handle Exception in Right Way

Exception hand is one of an integral part of any programming. PHP provides the feature of exception handling like other programming languages from its version 5 with renowned PHP try catch method. In this tutorial of PHP try catch, we will explore what is exception & what is exception handling. How to handle exception using PHP try catch.

The tutorial is for beginners who want to first know what exactly are the exceptions and how to handle the exception in PHP. In the beginning of the PHP try catch tutorial we will cover the basics and then advance topic like how to create custom Exception class and use.

What are exceptions in Programming?

Exceptions are the scenario in the programming language which breaks or interrupts the normal flow of your code or program. Exceptions occur at the time of execution of the program.

Suppose you are writing a program which is dividing the value by 10 and you are taking division as an input into your function. Like Below:
<?php
function divide_to_100($divisor){
return 100/$divisor;
}
?>

Now suppose someone has passed 0 as a divisor and called the function like below:
<?php
print divide_to_100(0);
?>

What will happen? Your program will generate a warning because of division by zero. This is one of the examples of exception in programming.

What is the exception Handling?

Exception handling is a method to handle the case in your programming which breaks the flow of your code on execution.The exception can be handled in the different ways as per the requirement of your program flow.

Now let us take the same example of devide_to_100 and handle the exception in different ways by putting a check of zero using php if else.

Method 1: Handle the exception via showing message:
<?php
function divide_to_100($divisor){
if($divisor == 0){
print 'Not allowed to divide by 0';
return;
}
return 100/$divisor;
}
print divide_to_100(0);
?>
Method 2: Trigger Error:
<?php
function divide_to_100($divisor){
if($divisor == 0){
trigger_error('Not allowed to devide by 0');
return;
}
return 100/$divisor;
}
print divide_to_100(0);
?>

Method 3: Throw a cachable Exception:
<?php
function divide_to_100($divisor){
if($divisor == 0){
throw new Exception('Can not divide by 0');
}
return 100/$divisor;
}
print divide_to_100(0);
?>

This is the exception handling method provided by PHP like other programming language. Above program will generate output like below:PHP ExceptionNote: My output is coloured because I have used xdebug. In your case it might be simple erroe text.You can also install Xdebug if you want.

In the complete tutorial of PHP try catch, we will only talk about the third method.

PHP Exception Handling

While writing your code logic you can throw exceptions using PHP exception class. While calling your logical code you can catch your exception and manipulate it into the desired ways. A thrown exception has to be an instance of inbuilt PHP Exception Class or Sub-Class of PHP Exception class. First, we will use inbuilt PHP exception class and in the later part of the tutorial, we will learn how to extend the inbuilt PHP Exception Class.

So let us again refer to our devide_to_100 function with method 3:
<?php
function divide_to_100($divisor){
if($divisor == 0){
throw new Exception('Can not divide by 0');
}
return 100/$divisor;
}
print divide_to_100(0);
?>
Now what we did is we are checking if $divisor == 0 and if it is true then throwing a new exception using inbuilt PHP exception class.
if($divisor == 0){
throw new Exception('Can not divide by 0');
}

What the code line throw new Exception(‘Can not devide by 0’); does? It is doing nothing but generating an exception and putting message ‘Can not devide by 0’.

But your above code will simply throw an error of “Uncaught Exception” and halting execution of the program. Is it good? Absolutely not. You should have some graceful message, sometimes you require to log your exception. Now how you will do that? You will do it by catching your exception using PHP try catch keyword. So let us see how to catch the exception.

PHP Try Catch to Catch the Exception

As we know that we can throw a catchable exception using PHP exception class. PHP also provides Try Catch keyword so that you can catch your exception and manipulate into the desired way.

Let us again refer to the same devide_to_100 function.
<?php
function divide_to_100($divisor){
if($divisor == 0){
throw new Exception('Can not divide by 0');
}
return 100/$divisor;
}
try{
divide_to_100(0);
}
catch(Exception $e){
echo $e->getMessage();
}
?>

In above code you can see that function is throwing an exception if divisor is zero. But while calling devide_to_100(0) we have called it in try{} blcok and then we have used catch(exception $e){} block where we are catching the exception and showing the message thrown by exception into the function using $e->getMessage();

Now let us see how it works.

How PHP Try Catch Works?

In the previous example we have used try and catch block and our error of uncaught exception gone. So let us understand how exactly PHP try catch works.

Try Code Block:

In the try{} block we write the code which needs to be executed. Now if any line of the code from the try block will throw any exception then catch block will come into the picture. All code inside the try block must be in curly braces. You can not write try block independently, it must have at least one catch or finally block. We will discuss finally keyword later on.

Catch Code Block

Catch code block is to catching the exception thrown by the code in the try block. In catch code block we specify the type or class of the exception we are catching with the object using catch(Exception $e). You can also use it like catch(Exception $ex) or like catch(Exception $err) where Exception is the name of the class of the exception which you are catching. If any exception will be identified into the try block the control will be passed to catch block. Catch code block will only get executed if any exception will be caught. If there will not be any exception then catch block code will not get executed. You can also use multiple catch block if you have more than one type of exception to handle.

Flow of code in PHP Try Catch Block

Let us take below example where exception will not occure:
<?php
function divide_to_100($divisor){
if($divisor == 0){
throw new Exception('Can not divide by 0');
}
return 100/$divisor;
}
try{
print divide_to_100(100);
}
catch(Exception $e){
echo $e->getMessage();
}
?>

So in above case your catch block code will not get executed.

With slight modification where exception will occur but there is code after the exception point:
<?php
function divide_to_100($divisor){
if($divisor == 0){
throw new Exception('Can not devide by 0');
}
return 100/$divisor;
}
try{
print 'Hello';//print Hello
print divide_to_100(0);//Exception case
print 'hi';//will not print hi
}
catch(Exception $e){
echo $e->getMessage();
}
?>

In the above we have written below try block:
try{
print 'Hello';//print Hello
print divide_to_100(0);//Exception case
print 'hi';//will not print hi
}

from the try block print ‘hi’ will not get executed this is because just before print ‘hi’ there is an exception and code control will go into the catch block.

You can also use try catch in a nested manner but every try block must have at least one catch or finally block.

If you are writing code into PHP namespace then you need to add the global namespace in the exception class. This is becuase Exception is inbuilt PHP class which is available in globl namespace. For example:
<?php
namespace Test;
function divide_to_100($divisor){
if($divisor == 0){
throw new \Exception('Can not divide by 0');
}
return 100/$divisor;
}
try{
print 'Hello';
print divide_to_100(0);
print 'hi';
}
catch(\Exception $e){
echo $e->getMessage();
}
?>

PHP Finally Keyword

From PHP 5.5 finally keyword is introduced. In finally keyword you can write code which will get executed regardless of whether exception was thrown or not. Finally code block can be created along with try and catch or you can use finally block just after try code block.

Below are the examples of php try catch and finally keyword:
try{
print "Hello\n";
print divide_to_100(0);
print "Hi\n";
}
catch(\Exception $e){
echo $e->getMessage();
}
finally {
print "handled try catch finally\n";
}

It will print:

Hello
Can not divide by 0
handled try catch finally

Throw Exception in Detail

If you will see divide_to_100 function’s throw exception code then you can found that we have defined message inside the exception.

throw new Exception('Can not divide by 0');

But while throwing the exception you can also define the code and previous parameter which are optional like below:

throw new Exception('Can not divide by 0' , 101, $previous);

PHP Builtin Exception Class

In the previous sections, we have used PHP try catch statement in everywhere and stated that we are using PHP exception class. In this section, we will discuss in detail of what is exception class what method and properties of the exception class we can use.

What is PHP Exception Class?

PHP Exception Class is a built-in class provided by PHP for the exception handling. PHP exception class has different methods and properties which we can use via handling Exception.

Let us take any catch block from above examples. We have catch block like below:
catch(Exception $e){
echo $e->getMessage();
}

So here in the above example, we have created an object of exception class with name $e. Also, in next line which is $e->getMessage() we have used method getMessage of Exception Class which return message thrown in the exception.

List of Methods of PHP Built-in Exception Class

MethodDescription
getMessage()Returns message thrown by exception
getCode()Returns exception code
getFile()Returns file name where exception was thrown
getLine()Returns line number of the exception
getTrace()Returns Array of backtrace
getPrevious()Returns previous exception
getTraceString()Returns formatted backtrace of the string

A detailed example of PHP Try Catch

As we have seen that PHP Exception class has lots of other function which we can use in our exception handling code to get the detailed exception. Below is a simple example of exception where different exception function is used.
<?php
function divide_to_100($divisor){
if($divisor == 0){
throw new Exception('Can not divide by 0' , '100');
}
return 100/$divisor;
}
try{
print divide_to_100(0);
}
catch(Exception $e){
print 'Exception Message '. $e->getMessage(). ' with exception code '.$e->getCode(). "\n";
print 'Exception in File '. $e->getFile(). ' at line number: '.$e->getLine()."\n";
print 'Detailed Back trace '. $e->getTraceAsString()."\n";
}
?>

 

Support Me by Sharing This Article

Ankur Kumar Singh

I am a PHP programmer having some knowledge about Linux. I am always interested in web development and knowledge sharing. I am full time tech evangelist part time human being. :-)

Leave a comment/Ask Question

shares