In PHP, structured exception handling is achieved through three keywords: try, catch, and finally. These blocks allow you to write code that can handle unexpected errors without crashing your entire application.
The basic idea is to "try" a block of code. If an exception occurs within that block, it is "caught" by a catch block, where you can handle the error gracefully.
<?php
try {
// Code that may throw an exception
} catch (Exception $e) {
// Code that runs if an exception is thrown
}
?>
The try block contains the code that you want to execute, but which might trigger an error. If an exception is thrown inside this block, the remaining code in the block is skipped, and execution jumps immediately to the catch block.
try block cannot stand alone; it must be followed by at least one catch block or a finally block.
The catch block is where you handle the exception. It defines the type of exception it can catch and assigns the exception object to a variable (usually $e or $exception).
<?php
function divide($dividend, $divisor) {
if($divisor == 0) {
throw new Exception("Division by zero error!");
}
return $dividend / $divisor;
}
try {
echo divide(10, 0);
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
?>
catch blocks to handle different types of exceptions in different ways.
The finally block is optional, but very useful. It contains code that will always run, regardless of whether an exception was thrown or caught. This is typically used for "cleanup" tasks, such as closing database connections or deleting temporary files.
<?php
try {
echo divide(10, 2);
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
} finally {
echo "This will always execute.";
}
?>
finally block executes even if the try or catch blocks contain a return statement.
In complex applications, you might want to handle different errors differently. You can stack multiple catch blocks for this purpose.
<?php
try {
// Some complex logic
if (!file_exists("data.txt")) {
throw new Exception("File not found!");
}
} catch (InvalidArgumentException $e) {
echo "Argument Error: " . $e->getMessage();
} catch (Exception $e) {
echo "General Error: " . $e->getMessage();
}
?>