PHP Exception Handling allows developers to manage runtime errors gracefully using structured error control mechanisms. Instead of stopping script execution abruptly, exceptions provide a clean way to detect and respond to problems.
When an exception is thrown inside a try block, PHP immediately stops executing the remaining code and looks for a matching catch block to handle it.
// General exception handling example
<?php
try {
$dividend = 10;
$divisor = 0;
if ($divisor == 0) {
throw new Exception("Division by zero not allowed.");
}
$result = $dividend / $divisor;
echo "Result: " . $result;
}
catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
?>
Since the divisor is zero, an exception is thrown. The catch block captures the exception and displays the error message instead of crashing the script.
You can modify the divisor value and observe how the output changes. Setting a valid divisor will allow the division to complete successfully.