0
0
PhpHow-ToBeginner · 3 min read

How to Use Try Catch in PHP: Simple Error Handling Guide

In PHP, use try to wrap code that might cause an error and catch to handle that error gracefully. This lets your program continue running even if something goes wrong inside the try block.
📐

Syntax

The try block contains code that might throw an exception. The catch block catches the exception and lets you handle it. You can have multiple catch blocks for different exception types.

php
try {
    // Code that may throw an exception
} catch (ExceptionType $e) {
    // Code to handle the exception
}
💻

Example

This example shows how to catch a division by zero error using try and catch. It prints a friendly message instead of stopping the program.

php
<?php
try {
    $a = 10;
    $b = 0;
    if ($b == 0) {
        throw new Exception("Division by zero is not allowed.");
    }
    $c = $a / $b;
    echo $c;
} catch (Exception $e) {
    echo "Caught exception: " . $e->getMessage();
}
?>
Output
Caught exception: Division by zero is not allowed.
⚠️

Common Pitfalls

  • Not throwing exceptions inside the try block means catch won't run.
  • Using a generic Exception catch can hide specific errors; catch specific exceptions when possible.
  • Forgetting to handle exceptions can cause the program to stop unexpectedly.
php
<?php
// Wrong: No exception thrown, catch block never runs
try {
    echo "No error here.";
} catch (Exception $e) {
    echo "This will not run.";
}

// Right: Throwing an exception to be caught
try {
    throw new Exception("Error happened.");
} catch (Exception $e) {
    echo "Caught: " . $e->getMessage();
}
?>
Output
No error here.Caught: Error happened.
📊

Quick Reference

Use try to test code that might fail, throw to create an error, and catch to handle it. Always catch specific exceptions when possible for clearer error handling.

KeywordPurpose
tryWrap code that may throw an exception
throwCreate an exception manually
catchHandle the exception thrown
ExceptionBase class for exceptions

Key Takeaways

Use try to wrap risky code and catch to handle errors gracefully.
Throw exceptions inside try to trigger catch blocks.
Catch specific exceptions for better error control.
Without throwing exceptions, catch blocks won't run.
Proper error handling keeps your program running smoothly.