Saturday, June 13, 2026
HomeLanguagesHow to handle exceptions in PHP ?

How to handle exceptions in PHP ?

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.
RELATED ARTICLES

Most Popular

Dominic
32515 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6897 POSTS0 COMMENTS
Nicole Veronica
12013 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12109 POSTS0 COMMENTS
Shaida Kate Naidoo
7019 POSTS0 COMMENTS
Ted Musemwa
7262 POSTS0 COMMENTS
Thapelo Manthata
6976 POSTS0 COMMENTS
Umr Jansen
6964 POSTS0 COMMENTS