Difference Between Exception and Error In PHP

admin_img Posted By Bajarangi soft , Posted On 31-12-2020

An Error is an unexpected program result, which can not be handled by the program itself. That can be solved by using the issue in the code manually. An Error can be an infinite loop that can not be handled by the program itself so you have to manually repair that issue. There is an easy procedure to handle error i.e. using die() function

exception and error in php

Error: An Error is an unexpected program result, which can not be handled by the program itself. That can be solved by using the issue in the code manually. An Error can be an infinite loop that can not be handled by the program itself so you have to manually repair that issue. There is an easy procedure to handle error i.e. using die() function.
Syntax:

die("message")
Example:
<?php 

// Open file in read mode 
$file_var = fopen("myfile.txt", "r"); 

// Check for file existence 
if (!file_exists("myfile.txt")) { 
    die("Sorry Error!! file does not exists"); 
} 
else { 
    fopen("myfile.txt", "r"); 
} 

?> 
Exception: An Exception also is an unexpected result of a program but Exception can be handled by the program itself by throwing another exception. Exceptions should only be used with error conditions, where the error is non removal. There is an easy way to overcome the Exception by using try and catch method.
Syntax:
try {

}
catch {

}
Example:
 
<?php 

function valid_division($x, $y) { 
    
    if($y != 0) { 
        return true; 
    } 
    else { 
        throw new Exception("Why should not be equal to 0"); 
    } 
} 

try { 
    valid_division(2, 0); 
    
    // Try block will only run if 
    // there is no exception 
    echo "Valid division"; 
} 
catch(Exception $e) { 
    
    // Catch block will run if an 
    // exception occurs 
    echo "Error\n"; 
    echo $e->getmessage(); 
} 

?> 

Related Post