0
0
PHPprogramming~5 mins

Throwing exceptions in PHP

Choose your learning style9 modes available
Introduction

Throwing exceptions helps you handle errors in your program clearly and safely. It stops the program when something goes wrong and lets you fix or report the problem.

When a function gets an invalid input and cannot continue.
When a file you want to open does not exist.
When a database connection fails.
When a required resource is missing during program execution.
When you want to stop the program and show a clear error message.
Syntax
PHP
throw new Exception("Error message here");
Use throw followed by new Exception with a message.
The message explains what went wrong.
Examples
This throws an exception with the message 'Invalid user ID'.
PHP
throw new Exception("Invalid user ID");
This throws an exception when a file is missing.
PHP
throw new Exception("File not found: config.txt");
Sample Program

This program defines a function that divides two numbers. It throws an exception if the second number is zero. The try block runs the function, and the catch block catches and shows the error message.

PHP
<?php
function divide($a, $b) {
    if ($b == 0) {
        throw new Exception("Cannot divide by zero");
    }
    return $a / $b;
}

try {
    echo divide(10, 2) . "\n";
    echo divide(5, 0) . "\n";
} catch (Exception $e) {
    echo "Caught exception: " . $e->getMessage() . "\n";
}
?>
OutputSuccess
Important Notes

Always use try and catch blocks to handle exceptions safely.

Throwing exceptions stops the normal flow, so handle them to avoid program crashes.

Summary

Throw exceptions to signal errors clearly.

Use throw new Exception("message") to create an error.

Catch exceptions with try and catch to handle errors gracefully.