How to handle errors using try, catch and finally in PHP?

PHP uses exceptions to handle errors. You put risky code in a try block. If something goes wrong, the code throws an exception and PHP jumps to the catch block. The finally block runs always, with or without error.

<?php
function divide($a, $b) {
    if ($b == 0) {
        throw new Exception("Division by zero");
    }
    return $a / $b;
}

try {
    echo divide(10, 2) . "<br>";
    echo divide(5, 0) . "<br>";
} catch (Exception $e) {
    echo "Error: " . $e->getMessage() . "<br>";
} finally {
    echo "Done";
}
?>

Output:

Tutorials Class - Output Window

5
Error: Division by zero
Done

  • getMessage() gives the error text, and getLine() gives the line number.
  • You can use many catch blocks for different exception types.
  • In PHP 7 and above, serious errors are thrown as Error objects. Catch Throwable to catch both Exception and Error.

Basics of PHP errors are in PHP Errors.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.