Try Block:
PHP has a base class named Exception and exceptions are thrown from try block to Exception or subclass of Exception class.
Syntax:
{
//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:
{
//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:
{
//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.
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’.
//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.
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: