php

How to Apply Try Catch Block in PHP

Exception handling is a very important feature of any object-oriented programming. When any logical or system error arrives after executing any code then it is called an exception and the technique by which the coder can correctly handle the errors is called exception handling. It is used to avoid unexpected results from the end-users, improve the application security and handle predefined errors efficiently. This feature is supported by PHP from version 5. Try and catch block is used to handle exceptions in object-oriented programming. Try block is used to throw the exception if any error occurs and catch or finally block is used to handle the exception in PHP. This tutorial will help you to learn the use of exception handling of object-oriented programming by using PHP.

Try Block

PHP has a base class named Exception and exceptions are thrown from try block to Exception or subclass of Exception class.

Syntax:

try
{  
    //Main code
}

Catch Block

Catch block appears after try block. PHP supports multiple catch blocks to handle multiple exceptions. When any exception throws, then PHP tries to match with the first catch block, then the second catch block if not matches with the first one, and so on.

Syntax:

try
{  
    //Main code
}
catch (Exception $e)
{
    //Error handling code
}

Finally Block

Finally block can be used after or instead of catch block in PHP and this block executes when try block exits. Any normal or termination code can be added to this block after executing the code of try block.

Syntax:

try
{  
    //Main code
}
catch (Exception $e)
{
    //Error handling code
}  
finally
{
    //Normal code
}

Example-1: Using try-catch block for simple error

The following example shows the use of a try-catch block for a single exception. Create a PHP file with the following script. The value of query parameter ‘num’ has been read and checked in the try block. If the value is below 10, then the try block will throw an exception in the catch block. Otherwise, the value will be printed. Catch block will catch the exception and print the message send from the try block. If no query parameter passes, then the default value will be 100.

<?php
//Test the number is 10 or more
try
{
    if(isset($_GET['num']))
        //Read the value from the url  
        $n = $_GET['num'];
    else
        //Set the default value
        $n=100;

    if($n <10)
    {
        //If the exception throws then catch block will display the following error message
        throw new Exception("<br/><br/><center><h2>The number must be 10 or more.</center></h2>");
    }
    else
    {
        //Executes this line if no error appears.
        echo "<br/><br/><center><h2>The number is $n</center></h2>";
    }
}

//catch the exception from try block
catch(Exception $e)
{
    //Print the error message passed from try block
    echo $e->getMessage();
}
?>

Output:

Run the script without any query parameter.

http://localhost/phpcode/trycatch1.php

Run the script with a query parameter value that is less than 10.

http://localhost/phpcode/trycatch1.php?num=5

Run the script with a query parameter value that is greater than 10.

http://localhost/phpcode/trycatch1.php?num=15

Example-2: Handling multiple errors by inheriting Exception class

Create a PHP file with the following script to handle the multiple exceptions by using multiple catch blocks. A subclass named ‘myException’ has been created by extending the base class ‘Exception’ to handle the ‘Invalid URL error’. The base class Exception has been used for handling ‘Empty URL error’.

<?php

//Declare a subclass myException by extending Exception class
class myException extends Exception {
   
    //set the error message in the constructor     
    public function __construct($message = null, $code = 0) {
        $this->message = $message; 
   
    }
   
    //display the error message
        public function display_error()
    {  
        echo '<br/><br/><center><h2>'.$this->message.' is not a valid URL address</center></h2>';
    }
}

try
{
    //set the url address using query parameter or default value
    $url=isset($_GET['url'])?$_GET['url']:"https://linuxhint.com";
   
    //check the url address is empty or not
    if($url == "") {
        //If the url address is empty then the following error message will throw
        throw new Exception("<br/><br/><center><h2>URL address is empty.</center></h2>");
    }
   
    //check the url addresss is valid or invalid
    elseif (!filter_var($url, FILTER_VALIDATE_URL)) {
        //If the url address is invalid then an exception will throw with invalid url address
        throw new myException($url);
    }
   
    else
    {
        //print message for valid url address
        echo "<br/><br/><center><h2>".$url." is a valid url address</center></h2>";
    }

}

//handle invalid url exception
catch(myException $e) {
   
    //call the method of subclass to print the error message
    echo $e->display_error();
}
//handle empty url exception
catch(Exception $e)
{
    //print error message for empty url address
    echo $e->getMessage();
}
?>

Output:

Run the script without any query parameter.

http://localhost/phpcode/trycatch2.php

Run the script with a query parameter named url without any value.

http://localhost/phpcode/trycatch2.php?url=

Run the script with a query parameter named url with an invalid URL value.

http://localhost/phpcode/trycatch2.php?url=google

Run the script with a query parameter named url with a valid URL value.

http://localhost/phpcode/trycatch2.php?url=http://google.com
Image

Example-3: Handling file error by using try, catch and finally block

Create a PHP file with the following script to know the use of try, catch and finally block. The script will try to open the file ‘test.txt’ and try block will throw an exception if the file does not exist in the current location or is unable to open. The catch block will print the error message thrown from the try block. The code of the finally block will close the file handler after executing the try block. Try block will print the content of the file if no error appears.

<?php
error_reporting(0);
try
{
    //Try to open a file for reading   
    $file_handler = fopen("test.txt", "r");    
    if(!$file_handler)
    {
        //Throw the exception if the file is unable to open
        throw new Exception("<br/><center><h2>Unable to open the file.</center></h2>");
    }
    else
    {
        //Print the centent of the file
        while(!feof($file_handler))
        {
            echo fgets($file_handler) . "<br>";
        }
        fclose($file_handler);

    }
}
catch (Exception $e) {
    //Print the error message for opening file error exception 
    echo $e->getMessage();
}
finally
{
    //print termination message
    echo "<center>Program terminated.<center>";
}
?>

Output:

Run the script.

http://localhost/phpcode/trycatch3.php

Example-4: Using nested try-catch block

Create a PHP file with the following script to know the way of using the nested try-catch block. The script will check the value taken from a URL is a number or not in the first try-catch block and the taken number is greater than 100 or not will be checked in the second try-catch block.

<?php

if(isset($_GET['n']))
{
    //The first try block
    try{
        $number = $_GET['n'];
        if (is_numeric($number))
        {
            //The second try block
            try{
                if($number >= 100){
                    //Print the success message
                    echo "The number is valid.";
                }
                else {
                    throw new Exception('The number is invalid.');  
                }
            }
            catch (Exception $e){
                //Print the second error
                echo $e->getMessage();
            }
        }
        else
        {
            throw new Exception('The value is not a number.');
        }
    }
    catch (Exception $e){
        //Print the firt error
        echo $e->getMessage() . "<br/>";
    }
}
else
    echo "No number has given.";
?>

Output:

Run the script without any query parameter.

http://localhost/phpcode/trycatch4.php

Run the script with the query parameter value less than 100.

http://localhost/phpcode/trycatch4.php?n=78

Run the script with the query parameter value greater than 100.

http://localhost/phpcode/trycatch4.php?n=112

Example-5: Using try-catch block with the function

Create a PHP file with the following script to know the use of the try-catch block with the function. The script will take two numeric values from the URL query parameters and the try-catch block will call a function that will throw an exception if the “Division by zero” error has occurred.

<?php
//Define function for calculating division
function division($a, $b) {
    $result = $a/$b;
    if(!$result)
        //Throw exception for the invalid result
        throw new Exception('Division by zero.');
    else
        echo "<h3>The result of $a/$b = $result</h3>";
}
if(isset($_GET['n1']) && isset($_GET['n2']))
{
    try {
         $number1 = $_GET['n1'];
         $number2 = $_GET['n2'];
         //Call function that will check error
         division($number1,$number2);  
    }
    catch(DivisionByZeroError $e) {
        //Print the error message
        echo '<h3> Error: </b>',  $e->getMessage(), "</h3>";
    }
}
else
    echo "One or more numbers have not been provided.";
?>

Output:

Run the script without any query parameter.

http://localhost/phpcode/trycatch5.php

Run the script with the query parameter values, 10 & 5.

http://localhost/phpcode/trycatch5.php?n1=10&n2=5

Run the script with the query parameter values, 10 & 0.

http://localhost/phpcode/trycatch5.php?n1=10&n2=0

Example-6: Display error message in detail for custom exception

Create a PHP file with the following script to display the error message in detail by using different methods of the exception class. The script will take the filename from the URL parameter and check the file exists or not by using a try-catch block.

<?php
if(isset($_GET['fn']))
{
    try {
     
      $filename = $_GET['fn'];
      if(!file_exists($filename))
      {
          throw new Exception('File does not exist.');
      }
    }

    catch (Exception $e) {
      //display error message in details
      echo '<br/>File Name: '.$e->getFile().
           '<br/>Error occured on Line number: '.$e->getLine().
           '<br/>Error Message: '.$e->getMessage();
    }

    finally {
      echo "<br/>Check another file.";
    }
}
else
    echo "Filename has not given.";
?>

Output:

Run the script without any query parameter.

http://localhost/phpcode/trycatch6.php

Run the script with the query parameter that contains the non-existing filename.

http://localhost/phpcode/trycatch6.php?fn=text.txt

Run the script with the query parameter that contains the existing filename.

http://localhost/phpcode/trycatch6.php?fn=trycatch5.php

Conclusion

The basic uses of the try-catch block have been explained in this tutorial by using very simple PHP scripts. I hope the concept of exception handling in PHP will be cleared after practicing the examples of this tutorial properly.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.