0
0
PHPprogramming~5 mins

Try-catch execution flow in PHP

Choose your learning style9 modes available
Introduction

Try-catch helps your program handle errors without stopping suddenly. It lets you catch problems and decide what to do next.

When you want to open a file but the file might not exist.
When you call a function that might fail, like connecting to a database.
When you want to check user input and handle wrong data safely.
When you want to keep your program running even if something goes wrong.
Syntax
PHP
try {
    // code that might cause an error
} catch (Exception $e) {
    // code to handle the error
}

The try block contains code that might cause an error.

The catch block runs only if an error happens in the try block.

Examples
This example shows a try block that runs fine, so catch does not run.
PHP
<?php
try {
    echo "Hello!";
} catch (Exception $e) {
    echo "Error caught.";
}
?>
This example throws an error on purpose, so the catch block runs and prints the message.
PHP
<?php
try {
    throw new Exception("Oops!");
} catch (Exception $e) {
    echo "Caught: " . $e->getMessage();
}
?>
Sample Program

This program tries to divide two numbers. If the second number is zero, it throws an error. The catch block catches it and returns a friendly message.

PHP
<?php
function divide($a, $b) {
    try {
        if ($b == 0) {
            throw new Exception("Cannot divide by zero.");
        }
        return $a / $b;
    } catch (Exception $e) {
        return "Error: " . $e->getMessage();
    }
}

echo divide(10, 2) . "\n";
echo divide(5, 0) . "\n";
?>
OutputSuccess
Important Notes

Only code inside the try block can cause the catch block to run.

You can have multiple catch blocks for different error types.

Always handle errors to keep your program user-friendly and safe.

Summary

Try-catch lets you handle errors without stopping your program.

Put risky code inside try, and error handling inside catch.

This helps your program stay strong and clear when problems happen.