PHP
Summary - Error handling
Build an age-checking function with try/catch, throw and custom exceptions.
Summary - Error handling
In this group you learned the five pillars of exception handling: catching with try/catch, throwing with throw, the Exception methods, choosing levels with error_reporting and writing custom exception classes.
Combined, they form a robust age check: you define a custom exception, throw it when a condition fails, catch it with try/catch and show a meaningful message to the user.
The last step is a mini app that puts the whole flow together.
Combine the age check
An age check has three parts: define (a custom exception), throw (when the condition fails) and catch (with try/catch).
First write InvalidAgeException extends Exception. Then, inside the verifyAge(int $age) function, if age is under 18, call throw new InvalidAgeException(...).
Finally call try { verifyAge(15); } and print the message with catch (InvalidAgeException $e).
Exercise Summary - Age check mini app
Define the InvalidAgeException class with extends Exception. Write a verifyAge(int $age): void function: if age is under 18, throw new InvalidAgeException("Too young"). Call verifyAge(15) inside try/catch, catch the error and print its message.
Show example solution
void; if ($age < 18) throw new InvalidAgeException("Too young"). Then try { verifyAge(15); } catch (InvalidAgeException $e) { echo $e->getMessage() . "\n"; }.
Example solution:
<?php
// Define InvalidAgeException and verifyAge
class InvalidAgeException extends Exception {
}
function verifyAge(int $age): void {
if ($age < 18) {
throw new InvalidAgeException("Too young");
}
echo "Welcome\n";
}
try {
verifyAge(15);
} catch (InvalidAgeException $e) {
echo $e->getMessage() . "\n";
}
Test yourself
-
Match the five pillars
- try/catch
- Catches the exception
- throw
- Throws the exception
- getMessage()
- Reads the message
- error_reporting
- Selects the levels
- extends Exception
- Derives a custom class
-
Throw in the age check
<?php
function verifyAge(int $age): array {
if ($age < 18) {
____ new InvalidAgeException("Too young");
}
return ['ok' => true];
}
Show answer
<?php
function verifyAge(int $age): array {
if ($age < 18) {
throw new InvalidAgeException("Too young");
}
return ['ok' => true];
}
Next lesson: Formatting dates with date()