In PHP, exceptions provide a structured and maintainable way to handle runtime errors. Using the throw keyword, you can immediately interrupt normal execution and transfer control to a corresponding catch block.
The throw statement creates an instance of the Exception class (or a subclass). PHP then looks for the nearest matching catch block. If none is found, the script terminates with a fatal error.
// Function that throws an exception for negative numbers
<?php
function checkNumber($number) {
if ($number < 0) {
throw new Exception("Negative numbers are not allowed: $number");
}
echo "Number is: $number<br>";
}
try {
checkNumber(10);
checkNumber(-5);
}
catch (Exception $e) {
echo "Caught exception: " . $e->getMessage();
}
?>
The first function call runs normally. The second call throws an exception, immediately stopping execution inside try and transferring control to catch, where the error message is displayed.
Imagine exceptions as emergency exits in your program. Once triggered, PHP jumps directly to the error-handling logic instead of continuing blindly. This keeps applications stable and predictable.