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

PHP try-catch

try-catch is like a safety net under a trapeze: you try something risky, and if it fails, the catch part grabs the problem so the show goes on.
Syntax
php
try {
    // code that might fail
    throw new Exception("message");
} catch (Exception $e) {
    echo $e->getMessage();
} finally {
    // always runs
}

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 running this block; jump to `catch` if it throws
try {
    // Declare `$result`, set to `10 / 0`
    $result = 10 / 0;
// Catch DivisionByZeroError $e
} catch (DivisionByZeroError $e) {
    // Print `"Caught: " . $e->getMessage()` to the output
    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 running this block; jump to `catch` if it throws
try {
    // Throw a new `Exception` with message `"Something failed", 42`
    throw new Exception("Something failed", 42);
// Catch Exception $e
} catch (Exception $e) {
    // Print `$e->getMessage() . " (code: " . $e->getCode() . ")"` to the output
    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
// Define the function `checkAge` taking `$age`
function checkAge($age) {
    // Check whether `$age < 0`
    if ($age < 0) {
        // Throw a new `Exception` with message "Age cannot be negative"
        throw new Exception("Age cannot be negative");
    }
    // Return `$age` from this function
    return $age;
}
// Try running this block; jump to `catch` if it throws
try {
    // Call `checkAge(-5)`
    checkAge(-5);
// Catch Exception $e
} catch (Exception $e) {
    // Print `$e->getMessage()` to the output
    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 running this block; jump to `catch` if it throws
try {
    // Throw a new `InvalidArgumentException` with message "Bad input"
    throw new InvalidArgumentException("Bad input");
// Catch InvalidArgumentException $e
} catch (InvalidArgumentException $e) {
    // Print `"Specific: " . $e->getMessage()` to the output
    echo "Specific: " . $e->getMessage();
// Catch Exception $e
} catch (Exception $e) {
    // Print `"General: " . $e->getMessage()` to the output
    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 running this block; jump to `catch` if it throws
try {
    // Print "Trying...\n" to the output
    echo "Trying...\n";
    // Throw a new `Exception` with message "Failed"
    throw new Exception("Failed");
// Catch Exception $e
} catch (Exception $e) {
    // Print "Caught: " . $e->getMessage() . "\n" to the output
    echo "Caught: " . $e->getMessage() . "\n";
// Runs no matter what, whether or not an exception was thrown
} finally {
    // Print "Cleanup always runs" to the output
    echo "Cleanup always runs";
}
?>
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Catching an exception and leaving the catch block empty, which hides the error completely.
  2. Putting a general catch (Exception $e) before specific catch blocks, so the specific ones never run.
  3. Expecting try/catch to catch ordinary warnings and notices, which are not exceptions unless you convert them.
🔒

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.