PHP
Throwing exceptions with throw
Learn to throw your own exception with throw new Exception().
What does throw do?
Sometimes you want to throw errors from your own conditions: an invalid age, a missing field, an unauthorized request. You throw an exception with throw.
throw new Exception('message') creates a new Exception object and throws it. Code execution stops right there; if a matching catch exists, flow jumps there, otherwise the script errors out.
The exception object carries a message; catch reads it with $e->getMessage().
Exception message and code
The Exception constructor takes two arguments: a message and a code. For example, new Exception('Too young', 18).
The message is a human-readable explanation of the error. In the catch block you read it with $e->getMessage(); it is shown to the user or written to a log.
The message should be short and clear: it must say what went wrong. The code is a numeric identifier.
Exercise Throw and catch an age check
Define a checkAge(int $age): void function: if age is under 18, throw new Exception("Too young"). Then call checkAge(15) inside try/catch, catch the error and print its message.
Show example solution
void; if ($age < 18) call throw new Exception("Too young"). Then write try { checkAge(15); } catch (Exception $e) { echo $e->getMessage() . "\n"; }.
Example solution:
<?php
// Write checkAge and call it with try/catch
function checkAge(int $age): void {
if ($age < 18) {
throw new Exception("Too young");
}
echo "Welcome\n";
}
try {
checkAge(15);
} catch (Exception $e) {
echo $e->getMessage() . "\n";
}
Test yourself
-
Which is a valid throw statement?
- throw Exception('Error');
- throw new 'Error';
- throw new Exception('Error');
- new throw Exception('Error');
Show answer
throw new Exception('Error'); — Correct. throw new Exception('message') creates and throws a new exception.
-
Complete the throw statement
<?php
function checkAge(int $age): array {
if ($age < 18) {
____ new Exception("Too young");
}
return ['ok' => true];
}
Show answer
<?php
function checkAge(int $age): array {
if ($age < 18) {
throw new Exception("Too young");
}
return ['ok' => true];
}
-
Match the throw and Exception concepts
- throw
- Throws the exception
- new Exception()
- Creates a new exception
- getMessage()
- Returns the message
- catch
- Catches the exception
-
What happens when throw is called?
- Code continues normal flow
- A warning is printed
- Only a log entry is written
- Execution stops and the exception propagates to the caller
Show answer
Execution stops and the exception propagates to the caller — Correct. throw stops execution and propagates the exception to the caller; a matching catch handles it.
Next lesson: The Exception class