How to Apply Try Catch Block in PHP

29/12/2020
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 exception and the technique by which the coder can handle the errors in proper way 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 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 first catch block, then second catch block if not matches with first one and so on.

Syntax:

try
{
    //Main code
}
catch (Exception $e)
{
    //Error handing 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 in this block after executing the code of try block.

Syntax:

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

Example-1: Exception handling using simple try-catch block

The following example shows the use of try-catch block for a single exception. Create a PHP file named ‘trycatch1.php’ under the folder ‘/var/www/html/phpcode’ and add the following script. The value of query parameter ‘num’  is read and checked in the try block. If the value is below 10 then the try block will throw a exception in the catch block otherwise the value will be printed. Catch block will catch the exception and print the message send from try block. If no query parameter passes then the default value will be 100.

//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: Exception handling using multiple catch block

Create a PHP file named ‘trycatch2.php’ under  the previous folder and add the following script to handle the multiple exceptions by using multiple catch blocks. A  subclass named ‘myException’ is created by extending base class ‘Exception’ to handle ‘invalid url error’. The base class Exception is 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 an valid url value.

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

Example-3: Exception handling using try, catch and finally block

Create a PHP file named ‘trycatch3.php’ under  the previous folder and add 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 is not exist in the current location or unable to open. Catch block will print the error message thrown from try block. The code of 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
 
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/><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>";
}
 
}
}
 
catch (Exception $e) {
//Print the error message for opening file error exception
echo $e->getMessage();
}
 
finally
{
//Close the file handler after executing the code of try block
fclose($file_handler);
}
 
?>

Output:

Run the script.

http://localhost/phpcode/trycatch3.php

The basic use of try-catch block are explained in this tutorial by using some simple code examples. Hope, the concept of exception handling in PHP will be cleared after reading this tutorial.

More info in this video:

ONET IDC thành lập vào năm 2012, là công ty chuyên nghiệp tại Việt Nam trong lĩnh vực cung cấp dịch vụ Hosting, VPS, máy chủ vật lý, dịch vụ Firewall Anti DDoS, SSL… Với 10 năm xây dựng và phát triển, ứng dụng nhiều công nghệ hiện đại, ONET IDC đã giúp hàng ngàn khách hàng tin tưởng lựa chọn, mang lại sự ổn định tuyệt đối cho website của khách hàng để thúc đẩy việc kinh doanh đạt được hiệu quả và thành công.
Bài viết liên quan

PHP Tutorial For Beginners

If you are new in PHP then this tutorials will help you to learn PHP from the beginning. PHP Basics: Hello World Comments Variables...
29/12/2020

PHP 7.1.3 released with lots of bug fixes – Install PHP 7 on Linux

PHP 7.1.3 recently released, is a popular general-purpose scripting language that is especially suited to web development....
28/12/2020

Install CakePHP on Ubuntu

Many MVC based PHP frameworks are available now to make web developing tasks simpler and easier than before. In an MVC...
28/12/2020
Bài Viết

Bài Viết Mới Cập Nhật

SỰ KHÁC BIỆT GIỮA RESIDENTIAL PROXY VÀ PROXY DATACENTER
17/02/2024

Mua Proxy v6 US Private chạy PRE, Face, Insta, Gmail
07/01/2024

Mua shadowsocks và hướng dẫn sữ dụng trên window
05/01/2024

Tại sao Proxy Socks lại được ưa chuộng hơn Proxy HTTP?
04/01/2024

Mua thuê proxy v4 nuôi zalo chất lượng cao, kinh nghiệm tránh quét tài khoản zalo
02/01/2024