Exception handling in PHP is a way to handle errors gracefully and ensure the application doesn’t crash when something goes wrong. It uses try, catch, and optionally finally blocks to manage exceptions.
Here’s how it works:
- Throwing an Exception: If an error occurs, you can “throw” an exception using the
throwkeyword. - Catching an Exception: The
tryblock contains code that may throw an exception. Thecatchblock handles the exception. - Finally Block (Optional): The
finallyblock contains code that will always execute, regardless of whether an exception was thrown or not.
Syntax
try {
// Code that may throw an exception
} catch (Exception $e) {
// Code to handle the exception
} finally {
// Code that always executes (optional)
}
Example 1: Simple Exception Handling
<?php
function divide($a, $b) {
if ($b == 0) {
throw new Exception("Division by zero is not allowed.");
}
return $a / $b;
}
try {
echo divide(10, 2); // This will work
echo divide(10, 0); // This will throw an exception
} catch (Exception $e) {
echo "Caught exception: " . $e->getMessage();
} finally {
echo " - End of division operation.";
}
?>
Output:
5 - Caught exception: Division by zero is not allowed. - End of division operation.
Example 2: Using Custom Exceptions
You can create custom exception classes by extending the base Exception class.
<?php
class CustomException extends Exception {}
function checkNumber($number) {
if ($number > 100) {
throw new CustomException("The number is too large.");
}
return "The number is acceptable.";
}
try {
echo checkNumber(50); // This will work
echo checkNumber(150); // This will throw a custom exception
} catch (CustomException $e) {
echo "Caught custom exception: " . $e->getMessage();
} catch (Exception $e) {
echo "Caught general exception: " . $e->getMessage();
} finally {
echo " - Validation complete.";
}
?>
Output:
The number is acceptable. - Caught custom exception: The number is too large. - Validation complete.
Key Points:
throwkeyword: Used to signal that an error has occurred.tryblock: Code that might throw an exception.catchblock: Code that handles the thrown exception.finallyblock: Code that runs regardless of an exception.- Custom Exceptions: Extend the
Exceptionclass for specialized error handling.
Exception handling makes PHP code more robust and easier to debug.

Ankit Srivastava is an IT trainer, technology educator, and digital skills mentor with expertise in programming, data analytics, AI, and software development. He has successfully trained thousands of learners, with more than 10,000 student enrollments on Udemy. His practical teaching approach empowers students and professionals to build in-demand technical skills. Colorstech channel where Ankit posts video tutorials has more than 8000 Subscribers.



