Open In App

How to handle exceptions in PHP ?

Improve
Improve
Like Article
Like
Save
Share
Report

Exceptions in PHP: The exception is the one that describes the error or unexpected behavior of the PHP script. The exception is thrown in many PHP tasks and classes. User-defined tasks and classes can also do differently. The exception is a good way to stop work when it comes to data that it can use.

Throw Exceptions in PHP: The throw statement in PHP allows for a defined function or method to do otherwise. If alternatives are thrown, the following code will not be used. If the exception is not detected, a dangerous error will occur with the message “Uncaught Exception”.

Example 1:

PHP




<?php
      
function division_operation($dividend, $divisor) {
    if($divisor == 0) {
        throw new Exception("Divide by Zero Error");
    }
    return $dividend / $divisor;
}
  
echo division_operation(12, 0);
?>


Output:

Example 2: The following example demonstrates the use of the PHP try…catch statement to avoid the above scenario.

PHP




<?php
      
function division_operation($dividend, $divisor) {
    if($divisor == 0) {
        throw new Exception("Raise Exception : Division by 0");
    }
    return $dividend / $divisor;
}
  
try {
    echo division_operation(12, 0);
} catch(Exception $e) {
    echo "Exception is Caught! : Unable to divide by 0";
}
?>


Output:

Exception is Caught! : Unable to divide by 0

Handling exceptions using try … catch … finally:

Example 3: In the following code, whatever is present in the “finally” statement will be executed regardless of the exception.

PHP




<?php
      
function division_operation($dividend, $divisor) {
    if($divisor == 0) {
        throw new Exception("Raise Exception : Division by 0");
    }
    return $dividend / $divisor;
}
  
try {
    echo division_operation(12, 0);
} catch(Exception $e) {
    echo "Exception is Caught! : Unable to divide by 0........";
}
finally {
    echo "Finally block execution - Process complete.";
}
?>


Output:

Exception is Caught! : Unable to divide by 0........Finally 
                       block execution - Process complete.


Last Updated : 03 Mar, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads