Difference between try-catch and if-else statements in PHP

The try and catch are used in PHP for handling exceptions like other languages such as C++, Java, etc. An exception is unexpected result or unexpected state of a program that can be handled by the program itself. To handle this kind of unexpected results in PHP, try and catch are used. For more details, visit Exception Handling in PHP.

Similarly, PHP also executes conditional statements using if and else to handle decision making scenarios. For more details, visit PHP | Decision Making

Differences between ‘try-catch’ and ‘if-else’ in PHP:

What are ‘if’ and ‘else’?

  • if: It checks if any condition is “true” or not, if it is true then it executes the code inside the if block.
  • else: If the condition is “false” which is checked by the if block, then else block executes the other code within it.
if(condition)
{......}
else
{......}

or



if(condition)
{......}
else if(condition)
{......}
else
{......}

What are ‘try’ and ‘catch’?

  • try: It is a section where a block of code is defined for tested whether the code generates an unexpected result while executing.
  • catch: It is a section where another block of code is defined, which is executed if any unexpected result generates in the try block. Actually this block of code handles the exceptions.
    try
    {...condition...;
     ...condition..;
     .....;
     .....;
     .....;
    }
    catch (Exception)
    {...handling exception...;}
    

Error Handling: Mainly if-else block is used to handle errors using condition checking. if-else catch errors as a conditional statement. In many cases there are many corner cases which must be checking during a execution but “if-else” can only handle the defined conditions. In if-else, conditions are manually generated based on the task.

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php 
  
$g = "GeeksforGeeks"
  
// Checks for a condition if
// 'g'is null or not
if ($g != "") { 
    echo $g
  
else
    echo "This is not the string"
?> 

chevron_right


Output:

GeeksforGeeks

In case of try-catch block, it will check the system generated errors or exception during an executing process or a task. These errors or exceptions are not manually generated. try-catch handles the exceptions that are easily readable.

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php 
  
// Exception handling function
function tryCatchException($b, $var) { 
      
    try {
        echo "\nDivition is ", $b/$var;
        throw new Exception('denominator is 0');
        // If 'var' is zero then exception
        // is thrown 
    
    // Catch block will be executed if
    // any Exception has been thrown 
    // by try block 
    catch(Exception $e) { 
        echo "\nException: ", $e->getMessage(); 
        // Print the Message passed 
        // by the thrown statement
    }
  
// Exception will happened
tryCatchException(6, 0); 
  
?> 

chevron_right


Output:

Runtime Errors : 
PHP Warning:  Division by zero in 
/home/1027ff9c161eb6503f545005908318fc.php on line 8
Divition is INF
Exception: denominator is 0 

Use one block to handle errors or exception: In case of if-else we have one else block corresponding to one if block, so we have to define each if block with a else block to handle “false” conditions. Also there may not be any else statement after if.

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php 
  
function rngeLaptop($a) {
  
    // Each 'if' with one 'else'
    if ($a == "Gaming") { 
        echo "Range stated from 50000rs\n"
    
       
    else if($a == "Education") {
        echo "Range stated from 25000rs\n"
    }
   
    else if($a == "Graphics works") {
        echo "Range stated from 55000rs\n"
    }
       
    else if($a == "Entertainment") {
        echo "Range stated from 18000rs\n"
    }
    else
        echo "Not listed\n"
    
}
  
rngeLaptop("Gaming");
rngeLaptop("Education");
rngeLaptop("Movie"); // Not listed
rngeLaptop("Entertainment");
rngeLaptop("Graphics works");
   
?> 

chevron_right


Output:

Range stated from 50000rs
Range stated from 25000rs
Not listed
Range stated from 18000rs
Range stated from 55000rs

In case of try-catch, we don’t have to define each try with a catch. There can be multiple exceptions defines inside one try and to catch the exceptions thrown by the try block, there can be one catch block.

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php 
   
// Exception handling function
function tryCatchException($b, $var) { 
    try {
          
        // Checking 2 condition and throwing
        // all exceptions in one catch block 
        if($var == 0) {
            throw new Exception('denominator is 0');
        }
        if($var < 0) {
            throw new Exception('denominator is a negative');
        }
        echo "\nDivition is ", $b/$var;
    
           
    // Catch block will be executed if any 
    // Exception has been thrown by try block 
    catch(Exception $e) { 
              
        // Print the Message passed by
        // the thrown statement   
        echo "\nException: ", $e->getMessage(); 
    }
}
   
// Exception will happened
tryCatchException(6, -3); 
tryCatchException(12, 0);
tryCatchException(15, 3); 
   
?> 

chevron_right


Output:

Exception: denominator is a string
Exception: denominator is 0
Divition is 5 

Brief discussion about the differences of ‘try-catch’ and ‘if-else’ in PHP:

if-else try-catch
It checks any condition is true or not, if true then execute the code inside the if block otherwise execute else block. ‘try’ is a section where a code is defined for tested whether the code generates an unexpected result while executing, if any unexpected result found catch block is executed to handle that situation.
‘if-else’ use to handle different conditions using condition checking. In case of ‘try-catch’, the system will check the system generated errors or exception during a executing process or a task.
Conditions are manually generated in ‘if-else’. according to the task. ‘try-catch’ handles system generated errors like, if a array is out of bound, divide by zero etc.
In ‘if-else’ the conditions and the codes inside the blocks are got mixed, so that it becomes unreadable if there is many ‘if-else’ blocks. In ‘try-catch’ the codes to handle the exceptions and what exception to be handled, that are easily readable.
In ‘if-else’, we have one else block corresponding to one if block. Or we need to define another condition with command ‘else if’. In ‘try-catch’ we don’t have to define each ‘try’ block with a ‘catch’ block.
‘if-else’ is less time consuming than ‘try-catch’. ‘try-catch’ is more time consuming than ‘if-else’.
‘if-else’ communicate between the data provided to the program and the condition. ‘try-catch’ communicate between the data with the conditions and the system.



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.