Exception Handling (try-catch)

🐘 PHP Lesson 14 Advanced

Exceptions capture runtime errors gracefully, allowing you to handle failures without crashing your application.

1 Try-Catch-Finally Blocks & Throwing Exceptions

PHP exception handling follows standard execution flows:

  • try: Wraps code blocks that may fail.
  • catch: Intercepts and handles errors if they occur.
  • finally: Executes cleanup code after try/catch, regardless of whether an error was thrown.
  • throw: Manually triggers exceptions using `throw new Exception("Message");`.
2 Exceptions Code

Let's run a program handling a division-by-zero error using try-catch blocks:

PHP — Exception Handling ▶ Run Code
<?php
function checkDivisor(int $number) {
    if ($number == 0) {
        throw new Exception("Division by zero error.");
    }
    return 100 / $number;
}

try {
    echo "Result: " . checkDivisor(5) . "\n";
    echo "Result: " . checkDivisor(0) . "\n"; // Throws exception
} catch (Exception $e) {
    echo "Exception Intercepted: " . $e->getMessage() . "\n";
} finally {
    echo "Finally execution block completed.\n";
}

echo "Program continues execution smoothly...\n";
?>
3 Code Challenge
Challenge: Write a custom function called `checkAge` that throws an `InvalidArgumentException` if age parameter is negative. Catch the exception inside a try-catch block and print its details.