PHP Try-Catch Blocks

PHP Try-Catch Blocks – Exception Handling Made Easy 🚀

Ever had a script crash and throw an ugly error message? 😱 Instead of letting errors ruin your day, use try-catch blocks to catch and handle them like a pro! 💪

PHP provides try and catch to deal with exceptions (unexpected errors) and prevent your script from breaking completely.


🔹 What is a Try-Catch Block?

A try-catch block is a way to “try” running some code and “catch” any errors that happen. This helps keep your application running smoothly.

📝 Basic Example: Using Try & Catch

Let’s handle an error gracefully using a try-catch block.

<?php
try {
    echo 10 / 0; // Oops! Division by zero causes an error
} catch (Exception $e) {
    echo "Caught an error: " . $e->getMessage();
}
?>

Try It Now

Oops! 🤦‍♂️ PHP doesn’t like dividing by zero, but our catch block prevents a crash.


🔹 Throwing an Exception

You can manually throw an exception using throw inside a try block.

📝 Example: Throwing and Catching an Exception

<?php
function checkAge($age) {
    if ($age < 18) {
        throw new Exception("Sorry, you must be 18+.");
    }
    return "Access granted!";
}

try {
    echo checkAge(16);
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}
?>

Try It Now

Result: This throws an error if the age is below 18.


🔹 Catching Multiple Exceptions

You can handle different types of exceptions separately using multiple catch blocks.

📝 Example: Handling Different Exceptions

<?php
try {
    throw new Exception("Something went wrong!");
} catch (InvalidArgumentException $e) {
    echo "Invalid argument: " . $e->getMessage();
} catch (Exception $e) {
    echo "Caught Exception: " . $e->getMessage();
}
?>

Try It Now

Tip: The most specific exception types should be caught first.


🔹 Using finally (Always Executes)

The finally block runs no matter what—whether an exception occurs or not.

📝 Example: Try, Catch & Finally

<?php
try {
    echo "Trying... <br>";
    throw new Exception("Oops! An error occurred!");
} catch (Exception $e) {
    echo "Caught: " . $e->getMessage() . "<br>";
} finally {
    echo "This always runs! ✅";
}
?>

Try It Now

Result: The finally block ensures that some code always runs.


🎯 Key Takeaways

  • try → Wraps risky code.
  • catch → Handles exceptions.
  • throw → Manually triggers an exception.
  • finally → Always executes, no matter what.

📝 Practice Time!

Try creating a function that throws an exception if an email is empty. Can you catch the exception and show a custom error message? 🤔