An exception is an object that signals an anomalous situation and interrupts the normal flow of the program.
In professional PHP development, moving away from die() or exit() and adopting Exceptions is a fundamental leap in quality. An exception is an object that describes an error or unexpected behavior, allowing your program to “react” and recover instead of stopping abruptly.
The flow is controlled by four essential keywords: try, catch, finally, and throw.
throw: throwing the problem
The throw keyword is used to indicate that an error has occurred. This stops the normal execution of the script at that point and looks for the first available catch block.
Note: In PHP, you can only “throw” objects that are instances of the
Throwableclass (typicallyExceptionorError).
function verifyAge($age) {
if ($age < 18) {
// Here we "throw" the exception. The code below this line does not execute.
throw new Exception("You must be of legal age to access.");
}
return "Access granted.";
}try and catch: trying and catching
To handle a thrown exception, we wrap the “dangerous” code (which might fail) inside a try block. If an exception occurs within the try, control immediately passes to the catch block.
try: Defines the code area to monitor.catch: Defines what to do if a specific error occurs. You can have multiplecatchblocks for different types of errors.
try {
// We attempt to execute the function
echo verifyAge(15);
} catch (Exception $e) {
// If it fails, we catch the error object in the variable $e
// We use methods of the Exception object like getMessage()
echo "Error caught!: " . $e->getMessage();
}finally: the cleanup block
The finally block is optional but very powerful. The code inside finally will always execute, whether an exception occurs or not.
It is ideal for cleanup tasks, such as closing database connections or closing open files, ensuring resources are not left “hanging.”
Complete integrated example
Imagine a function that performs a division. Mathematically, we know that division by zero is undefined.
function divide($numerator, $denominator) {
if ($denominator === 0) {
throw new Exception("Division by zero is not allowed.");
}
return $numerator / $denominator;
}
echo "--- Starting process ---\n";
try {
// 1. We attempt the operation (this will fail)
$result = divide(10, 0);
echo "The result is: " . $result;
} catch (Exception $e) {
// 2. We catch the error
echo "A problem has occurred: " . $e->getMessage() . "\n";
// We could log this error here
} finally {
// 3. This ALWAYS executes, error or not
echo "--- Cleaning memory and closing process ---\n";
}
echo "The script continues executing...";- --- Starting process ---
- A problem has occurred: Division by zero is not allowed. (The
echoof the result inside the try was skipped). - --- Cleaning memory and closing process ---
- The script continues executing… (The program did not fatally die).