Exception handling is a mechanism in PHP to handle runtime errors (exceptions) in a structured and controlled manner.
- It provides a way to transfer control from the point of error occurrence to a block of code that handles the error, ensuring the program does not terminate abruptly.
Common Built-in Exception Classes in PHP:
- Exception: The base class for all exceptions.
- ErrorException: For converting PHP errors into exceptions.
- LogicException: Represents problems in program logic (e.g., invalid arguments).
- RuntimeException: Represents runtime errors (e.g., database connection failures).
Advantages of Exception Handling:
- Error Isolation:
- Separates error-handling logic from regular code, improving readability.
- Custom Error Handling:
- Allows developers to define custom error-handling logic for different situations.
- Program Stability:
- Prevents the program from crashing due to unhandled errors.
- Reusability:
- Exception handling can be reused across multiple parts of the application.
Methods of exception handling in PHP:
- try Block
- catch Block
- throw Block
- finally Block
1.) try Block
The try block contains the code that might generate an exception.
- PHP executes the code inside the try block until an exception is thrown.
- If an exception occurs, PHP stops executing the remaining code in the try block and jumps to the appropriate catch block to handle the error.
try {
$result = divide(10, 0); // This line may throw an exception
echo $result;
} catch (Exception $e) {
echo $e->getMessage(); // Handles the exception
}
2.) catch Block
The catch block contains code that handles the exception thrown in the try block.
- If an exception is thrown, PHP will check if the type of exception matches the one specified in the catch block. If matched, the catch block is executed.
try {
$result = divide(10, 0);
} catch (Exception $e) {
echo "Caught exception: " . $e->getMessage();
}
3.) throw Keyword
The throw keyword is used to manually throw an exception from the code.
- When an exception is thrown, it is caught by the nearest catch block in the call stack.
function divide($num1, $num2) {
if ($num2 == 0) {
throw new Exception("Division by zero is not allowed."); // Throwing an exception
}
return $num1 / $num2;
}
try {
echo divide(10, 0); // This will throw an exception
} catch (Exception $e) {
echo $e->getMessage(); // Handles the exception
}
4.) finally Block (Optional)
The finally block contains code that always executes after the try and catch blocks, regardless of whether an exception was thrown or caught.
function divide($num1, $num2) {
if ($num2 == 0) {
throw new Exception("Cannot divide by zero.");
}
return $num1 / $num2;
}
try {
echo divide(10, 2);
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
} finally {
echo "Execution completed."; // Always executes
}
Key Flow:
- PHP attempts to execute the code in the try block.
- If no exception occurs, it skips the catch block and moves to the finally block (if present).
- If an exception occurs, the execution jumps to the matching catch block.
- Regardless of whether an exception occurs or not, the finally block is executed after the try and catch blocks.