What is exception handling? How do you handle exception / errors in PHP? Describe with syntax and examples.

Exception Handling is a mechanism used to detect and handle runtime errors (exceptions) so that a program does not terminate unexpectedly. It allows developers to separate normal program logic from error-handling code.

In PHP, exceptions are handled using the following keywords:

  • try – Contains code that may throw an exception.
  • throw – Throws an exception when an error occurs.
  • catch – Catches and handles the exception.
  • finally (optional) – Executes code regardless of whether an exception occurs.

Syntax

try {
// Code that may cause an exception
throw new Exception(“Error message”);
}
catch (Exception $e) {
// Handle the exception
echo “Exception: ” . $e->getMessage();
}
finally {
// Optional cleanup code
echo “This block always executes.”;
}

Example 1: Basic Exception Handling

<?php
function checkAge($age) {
if ($age < 18) {
throw new Exception(“You must be at least 18 years old.”);
}
return “Access granted.”;
}

try {
echo checkAge(15);
}
catch (Exception $e) {
echo “Error: ” . $e->getMessage();
}
?>

Error: You must be at least 18 years old.

Handling PHP Errors as Exceptions

PHP errors can also be converted into exceptions using set_error_handler().

<?php
set_error_handler(function($errno, $errstr) {
throw new ErrorException($errstr, 0, $errno);
});

try {
echo 10 / 0;
}
catch (Throwable $e) {
echo “Caught: ” . $e->getMessage();
}
?>

Advantages of Exception Handling

  • Prevents abrupt program termination.
  • Separates error-handling code from normal program logic.
  • Makes programs easier to debug and maintain.
  • Allows custom error messages.
  • Ensures cleanup code executes using finally.

Summary

Exception handling in PHP uses try, throw, catch, and optionally finally to manage runtime errors gracefully. By handling exceptions properly, applications become more robust, reliable, and easier to maintain.

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted