Introduction
Exception handling helps PHP developers manage unexpected problems without abruptly stopping a program. Using try, catch, and finally, you can detect exceptions, handle errors, and execute important cleanup code. In this chapter, you will practise Exception Handling in PHP through practical examples involving calculations, student records, employee data, files, and custom exceptions.
Question 1: Handle an Exception Using try and catch
Problem Statement
Create a PHP program that divides two numbers and handles an exception when the second number is zero.
PHP Solution
<?php
$num1 = 100;
$num2 = 0;
try {
if ($num2 == 0) {
throw new Exception("Division by zero is not allowed.");
}
echo "Result: " . ($num1 / $num2);
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
?>
Sample Output
Error: Division by zero is not allowed.
Explanation
trycontains the code that may generate an exception.throwcreates an exception.catchhandles the exception.getMessage()returns the exception message.
Concepts Covered
tryblockcatchblockthrowstatementExceptionclass
Question 2: Use Finally Block with Try-Catch
Problem Statement
Create a PHP program that handles an invalid age and displays a message from the finally block.
PHP Solution
<?php
$age = 15;
try {
if ($age < 18) {
throw new Exception("You are not eligible to register.");
}
echo "Registration successful.";
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
} finally {
echo "\nRegistration process completed.";
}
?>
Sample Output
Error: You are not eligible to register.
Registration process completed.
Explanation
- The
tryblock checks the user’s age. - If the age is below 18, an exception is thrown.
- The
catchblock displays the error message. - The
finallyblock executes whether an exception occurs or not.
Concepts Covered
finallyblock- Exception handling
- Program cleanup
Question 3: Handle Multiple Exceptions Using Multiple Catch Blocks
Problem Statement
Create a PHP program that checks a product quantity and price. Handle invalid quantity and invalid price using different exception messages.
PHP Solution
<?php
$quantity = -5;
$price = 500;
try {
if ($quantity <= 0) {
throw new InvalidArgumentException("Quantity must be greater than zero.");
}
if ($price <= 0) {
throw new DomainException("Price must be greater than zero.");
}
echo "Total Amount: " . ($quantity * $price);
} catch (InvalidArgumentException $e) {
echo "Quantity Error: " . $e->getMessage();
} catch (DomainException $e) {
echo "Price Error: " . $e->getMessage();
}
?>
Sample Output
Quantity Error: Quantity must be greater than zero.
Explanation
- Multiple
catchblocks can handle different exception types. InvalidArgumentExceptionhandles an invalid quantity.DomainExceptionhandles an invalid price.- PHP executes the matching catch block.
Concepts Covered
- Multiple catch blocks
InvalidArgumentExceptionDomainException- Exception types
Question 4: Use Finally to Close a File
Problem Statement
Create a PHP program that opens a file, reads its contents, and closes the file using the finally block.
PHP Solution
<?php
$file = null;
try {
$file = fopen("student.txt", "r");
if ($file === false) {
throw new Exception("Unable to open the file.");
}
echo fread($file, filesize("student.txt"));
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
} finally {
if (is_resource($file)) {
fclose($file);
echo "\nFile closed successfully.";
}
}
?>
Sample Output
Assuming student.txt contains Welcome to PHP.
Welcome to PHP
File closed successfully.
Explanation
fopen()opens the file.fread()reads its contents.fclose()closes the file.finallyensures the file-closing code is attempted even if an exception occurs.is_resource()checks whether the file handle is still a valid resource.
Concepts Covered
- File handling
fopen()fread()fclose()finallyblock
Question 5: Create a Custom Exception Class
Problem Statement
Create a custom exception class that checks whether a student’s marks are valid. Marks must be between 0 and 100.
PHP Solution
<?php
class InvalidMarksException extends Exception
{
}
$marks = 120;
try {
if ($marks < 0 || $marks > 100) {
throw new InvalidMarksException("Marks must be between 0 and 100.");
}
echo "Valid marks: " . $marks;
} catch (InvalidMarksException $e) {
echo "Marks Error: " . $e->getMessage();
}
?>
Sample Output
Marks Error: Marks must be between 0 and 100.
Explanation
InvalidMarksExceptionis a custom exception class.- It extends PHP’s built-in
Exceptionclass. throwcreates an object of the custom exception.- The matching
catchblock handles it.
Concepts Covered
- Custom exceptions
- Class inheritance
extends Exception- Exception messages
Question 6: Use Finally Even When No Exception Occurs
Problem Statement
Create a PHP program that calculates an employee’s annual salary and displays a final message even when the calculation is successful.
PHP Solution
<?php
$monthlySalary = 30000;
try {
$annualSalary = $monthlySalary * 12;
echo "Annual Salary: " . $annualSalary;
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
} finally {
echo "\nSalary calculation completed.";
}
?>
Sample Output
Annual Salary: 360000
Salary calculation completed.
Explanation
- The
tryblock performs the salary calculation. - No exception occurs, so the
catchblock is skipped. - The
finallyblock still executes. finallyis useful for cleanup and final operations.
Concepts Covered
- Successful execution
finallywithout an exception- Salary calculation
Question 7: Throw an Exception When a Bank Balance Is Insufficient
Problem Statement
Create a PHP program that allows a customer to withdraw money only when the account has sufficient balance.
PHP Solution
<?php
$balance = 5000;
$withdrawAmount = 7000;
try {
if ($withdrawAmount <= 0) {
throw new InvalidArgumentException("Withdrawal amount must be positive.");
}
if ($withdrawAmount > $balance) {
throw new Exception("Insufficient account balance.");
}
$balance = $balance - $withdrawAmount;
echo "Withdrawal successful.";
echo "\nRemaining Balance: " . $balance;
} catch (InvalidArgumentException $e) {
echo "Input Error: " . $e->getMessage();
} catch (Exception $e) {
echo "Transaction Error: " . $e->getMessage();
} finally {
echo "\nTransaction process completed.";
}
?>
Sample Output
Transaction Error: Insufficient account balance.
Transaction process completed.
Explanation
- The program checks whether the withdrawal amount is positive.
- It then checks whether sufficient balance is available.
- An exception is thrown if the withdrawal cannot be completed.
- The appropriate
catchblock displays the error. - The
finallyblock displays the transaction completion message.
Concepts Covered
- Business rule validation
- Multiple exceptions
- Bank balance calculation
- Transaction handling
Question 8: Re-Throw an Exception After Catching It
Problem Statement
Create a PHP program that catches an exception, displays a message, and throws the same exception again for another catch block to handle.
PHP Solution
<?php
try {
try {
throw new Exception("Employee record not found.");
} catch (Exception $e) {
echo "Initial Handler: " . $e->getMessage() . "\n";
throw $e;
}
} catch (Exception $e) {
echo "Final Handler: " . $e->getMessage();
}
?>
Sample Output
Initial Handler: Employee record not found.
Final Handler: Employee record not found.
Explanation
- The inner
tryblock throws an exception. - The inner
catchblock catches it. throw $esends the same exception to the outer handler.- The outer
catchblock handles it again.
Concepts Covered
- Nested try-catch
- Re-throwing exceptions
- Exception propagation
Question 9: Create a Custom Exception for Employee Salary
Problem Statement
Create a custom exception that prevents an employee from receiving a negative salary.
PHP Solution
<?php
class InvalidSalaryException extends Exception
{
}
$employeeName = "Amit";
$salary = -15000;
try {
if ($salary < 0) {
throw new InvalidSalaryException("Employee salary cannot be negative.");
}
echo "Employee: " . $employeeName;
echo "\nSalary: " . $salary;
} catch (InvalidSalaryException $e) {
echo "Salary Error: " . $e->getMessage();
} finally {
echo "\nEmployee salary verification completed.";
}
?>
Sample Output
Salary Error: Employee salary cannot be negative.
Employee salary verification completed.
Explanation
InvalidSalaryExceptiondefines a custom exception.- The program checks whether the salary is negative.
- If the condition is true, an exception is thrown.
- The custom catch block handles the exception.
- The finally block executes after exception handling.
Concepts Covered
- Custom exception class
- Salary validation
try-catch-finally- Exception handling in employee records
Question 10: Build an Employee Registration System Using Exception Handling
Problem Statement
Create a PHP employee registration program that validates the employee name, age, and salary. Use exceptions to handle invalid information and a finally block to display the completion message.
PHP Solution
<?php
$employeeName = "Rahul";
$age = 16;
$salary = 25000;
try {
if ($employeeName == "") {
throw new Exception("Employee name is required.");
}
if ($age < 18) {
throw new Exception("Employee must be at least 18 years old.");
}
if ($salary <= 0) {
throw new Exception("Salary must be greater than zero.");
}
echo "Employee Registered Successfully.";
echo "\nName: " . $employeeName;
echo "\nAge: " . $age;
echo "\nSalary: " . $salary;
} catch (Exception $e) {
echo "Registration Error: " . $e->getMessage();
} finally {
echo "\nRegistration process completed.";
}
?>
Sample Output
Registration Error: Employee must be at least 18 years old.
Registration process completed.
Explanation
- The program checks the employee’s name, age, and salary.
- An exception is thrown when any validation fails.
- The
catchblock displays the relevant error message. - If all validations pass, employee information is displayed.
- The
finallyblock executes in either case.
Concepts Covered
- Practical exception handling
- Input validation
- Multiple validation conditions
try-catch-finally- Employee registration system
Key Takeaways
- Exception handling manages unexpected situations in PHP programs.
- The
tryblock contains code that may throw an exception. - The
catchblock handles matching exceptions. - The
finallyblock executes after the try-catch sequence, whether an exception occurs or not. - The
throwstatement creates and throws an exception. - Multiple
catchblocks can handle different exception types. - Custom exception classes help create application-specific error handling.
- Exceptions can be re-thrown using
throw. getMessage()retrieves an exception’s message.- Exception handling makes PHP applications easier to maintain and debug.
Frequently Asked Questions (FAQs)
1. What is exception handling in PHP?
Exception handling is a technique used to manage unexpected situations in a program without allowing them to interrupt normal execution unnecessarily.
2. What is the purpose of the try block?
The try block contains code that may generate an exception. PHP checks this block for exceptions during execution.
3. What is the purpose of the catch block?
The catch block receives and handles an exception thrown inside the corresponding try block.
4. What is the finally block in PHP?
The finally block contains code that runs after the try-catch sequence, regardless of whether an exception was thrown or handled.
5. Is the finally block compulsory in PHP?
No. A finally block is optional. You can use try and catch without it.
6. Can we use multiple catch blocks in PHP?
Yes. Multiple catch blocks can handle different exception types in the same try-catch structure.
7. What is a custom exception in PHP?
A custom exception is a developer-created exception class that extends PHP’s built-in Exception class.
8. What is the difference between throw and catch?
throw generates and sends an exception, while catch receives and handles that exception.
9. Can we use try-catch inside another try-catch in PHP?
Yes. PHP supports nested try-catch blocks, allowing exceptions to be handled at different levels.
10. Why is exception handling important in PHP?
Exception handling helps developers manage unexpected problems, display meaningful messages, protect application workflows, and perform cleanup operations.
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
