← Back to PHP Course | Chapter 13: Error Handling | Lesson 2 of 5

PHP try-catch

Introduction to try-catch

A try-catch block lets you contain risky operations -- like a database call that might fail -- inside the try section, while the catch section defines what happens if something actually goes wrong, instead of the whole script crashing.

Example: Introduction to try-catch

php
<?php
try {
    $result = 10 / 0;
} catch (DivisionByZeroError $e) {
    echo "Caught: " . $e->getMessage();
}
?>

The Exception Object

Every caught Exception object carries useful diagnostic details -- its message, an optional error code, and the file and line where it was thrown -- which you can inspect to decide how to respond or what to log.

Example: The Exception Object

php
<?php
try {
    throw new Exception("Something failed", 42);
} catch (Exception $e) {
    echo $e->getMessage() . " (code: " . $e->getCode() . ")";
}
?>

Throwing Exceptions

The throw keyword is how your own code signals a problem, immediately halting normal execution and jumping to the nearest matching catch block, similar to how a runtime error would.

Example: Throwing Exceptions

php
<?php
function checkAge($age) {
    if ($age < 0) {
        throw new Exception("Age cannot be negative");
    }
    return $age;
}
try {
    checkAge(-5);
} catch (Exception $e) {
    echo $e->getMessage();
}
?>

Multiple catch Blocks

When you expect several distinct kinds of failure, stacking multiple catch blocks lets you handle each one differently -- just order them from most specific exception type to most general, since PHP checks them top to bottom.

Example: Multiple catch Blocks

php
<?php
try {
    throw new InvalidArgumentException("Bad input");
} catch (InvalidArgumentException $e) {
    echo "Specific: " . $e->getMessage();
} catch (Exception $e) {
    echo "General: " . $e->getMessage();
}
?>

The finally Block

Code inside a finally block always runs, whether the try succeeded or an exception was caught, which makes it the natural place for cleanup like closing a file handle or database connection.

Example: The finally Block

php
<?php
try {
    echo "Trying...\n";
    throw new Exception("Failed");
} catch (Exception $e) {
    echo "Caught: " . $e->getMessage() . "\n";
} finally {
    echo "Cleanup always runs";
}
?>
🔒

Chapter Quiz — Complete all 5 topics to unlock

0/5 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.