Introduction
Try Catch in PHP is used for exception handling. It helps developers manage errors in a controlled way without stopping the entire application. Using Try Catch improves application stability and provides better error messages for debugging.
Exception handling is commonly used in file handling, database connections, APIs, and user input validation.
Objectives
By the end of this training, you will be able to:
- Understand exception handling in PHP
- Use try and catch blocks correctly
- Handle runtime errors safely
- Display custom error messages
- Use finally blocks in PHP
- Create custom exceptions
What is Exception Handling
Exception handling is a method used to handle unexpected errors during program execution.
Instead of showing fatal errors to users, PHP allows developers to catch exceptions and respond properly.
Basic Syntax of Try Catch
<?php
try {
// Code that may cause an exception
}
catch(Exception $e) {
// Code to handle the exception
}
?>
Understanding the Try Block
The try block contains code that may generate an exception.
Example:
<?php
try {
$num = 10 / 0;
}
catch(Exception $e) {
echo "Error occurred";
}
?>
Understanding the Catch Block
The catch block handles exceptions generated in the try block.
Example:
<?php
try {
throw new Exception("Invalid operation");
}
catch(Exception $e) {
echo $e->getMessage();
}
?>
Output
Invalid operation
Using Multiple Catch Blocks
PHP allows handling different exception types separately.
<?php
try {
// Code
}
catch(TypeError $e) {
echo "Type Error";
}
catch(Exception $e) {
echo "General Exception";
}
?>
Finally Block in PHP
The finally block always executes whether an exception occurs or not.
<?php
try {
echo "Try Block";
}
catch(Exception $e) {
echo "Catch Block";
}
finally {
echo "Finally Block";
}
?>
Throwing Exceptions
The throw keyword is used to generate exceptions manually.
<?php
$age = 15;
try {
if($age < 18) {
throw new Exception("Age must be 18 or above");
}
}
catch(Exception $e) {
echo $e->getMessage();
}
?>
Creating Custom Exceptions
Developers can create their own exception classes.
<?php
class CustomException extends Exception {
}
try {
throw new CustomException("Custom Error Message");
}
catch(CustomException $e) {
echo $e->getMessage();
}
?>
Benefits of Try Catch
- Prevents application crashes
- Improves user experience
- Helps debug applications
- Makes code more secure
- Simplifies error handling
- Provides professional error management
Common Use Cases
Try Catch is commonly used in:
- Database connections
- File handling
- API integration
- Form validation
- Login systems
- Payment gateways
Best Practices
- Use meaningful error messages
- Avoid displaying sensitive system errors to users
- Use finally blocks for cleanup operations
- Handle specific exceptions separately
- Log errors for debugging purposes
Real World Example
<?php
try {
$conn = new PDO("mysql:host=localhost;dbname=test", "root", "");
echo "Database Connected";
}
catch(PDOException $e) {
echo "Connection Failed: " . $e->getMessage();
}
?>
Summary
Try Catch in PHP is an essential feature for managing errors and exceptions effectively. It improves application reliability, security, and user experience by handling unexpected problems in a controlled manner.