In production web development, errors are inevitable: a database server might go offline, a requested file might be deleted, or a user might enter invalid input. In legacy PHP, unhandled errors displayed ugly fatal crashes to visitors. Modern PHP utilizes structured Exception Handling using try, catch, finally, and custom Exception classes to gracefully capture runtime failures without halting the server.
try...catch...finally Construct<?php
function calculateSemesterDivision(int $totalMarks, int $totalSubjects): float {
if ($totalSubjects <= 0) {
// Throw an exception when an illegal condition occurs
throw new InvalidArgumentException("Number of subjects must be greater than zero.");
}
return $totalMarks / $totalSubjects;
}
try {
// Code that might fail
$average = calculateSemesterDivision(450, 0); // Will trigger exception!
echo "Calculated Average: " . $average;
} catch (InvalidArgumentException $e) {
// Gracefully catch and handle the specific error
echo "<div style='color:red;'>Calculation Error: " . $e->getMessage() . "</div>";
} finally {
// ALWAYS executes regardless of whether an error occurred
echo "<p>Calculation routine complete.</p>";
}
?>
In PHP 7.1+, you can catch multiple related exception classes in a single catch block using the pipe operator (|):
<?php
try {
// Complex database and file logic...
} catch (PDOException | IOException $e) {
// Handles both database and filesystem failures together
error_log($e->getMessage());
echo "A system infrastructure error occurred. Support has been notified.";
}
?>
<?php
// Custom domain exception
class StudentNotFoundException extends Exception {}
class StudentService {
public function findStudent(int $id): string {
if ($id !== 101) {
throw new StudentNotFoundException("Student with ID #$id was not found in college registry.");
}
return "Rahul Sharma";
}
}
try {
$service = new StudentService();
$student = $service->findStudent(999);
} catch (StudentNotFoundException $e) {
echo "Notice: " . $e->getMessage();
}
?>
High-Frequency Exam Question:
Q: What are the primary methods available on PHP's Exception object?
• $e->getMessage(): Returns the error message string.
• $e->getCode(): Returns the numeric error code.
• $e->getFile(): Returns the filename where the exception was thrown.
• $e->getLine(): Returns the source line number where error occurred.
• $e->getTraceAsString(): Formatted call stack backtrace.
Exercise 42.1: Create a custom InsufficientBalanceException that is thrown if a bank withdrawal exceeds account balance.
Exercise 42.2: Write a script that attempts to open a non-existent file, catching the exception and logging the error stack trace to an errors.log file.