Custom exception classes
Learn to define your own exception classes that extend Exception.
Write your own exception class
Sometimes you want to distinguish the type of error: an invalid email, an unauthorized request, missing stock. You do this by writing your own class that extends Exception.
class InvalidEmailException extends Exception {} creates an empty subclass. Now you can catch only this type with catch (InvalidEmailException $e).
Custom exceptions make error handling domain-specific.
Constructor and the parent call
When you add extra fields to a custom exception, the constructor must call parent::__construct(). This passes the message and code up to Exception.
Example: class InvalidEmailException extends Exception { public function __construct($email) { parent::__construct("Invalid email: $email"); } }
Now getMessage() returns your customized message. You can also add new methods to the class, so the error object gains behavior.
Exercise Custom exception class and usage
Define the InvalidEmailException class with extends Exception. Write a validateEmail(string $email): void function: if the email does not contain '@', throw new InvalidEmailException("Invalid email"). Call validateEmail("bad") inside try/catch, catch the error and print its message.
Show example solution
void; if (strpos($email, '@') === false) throw new InvalidEmailException("Invalid email"). Then try { validateEmail("bad"); } catch (InvalidEmailException $e) { echo $e->getMessage() . "\n"; }.
Example solution:
<?php
// Define InvalidEmailException and validateEmail
class InvalidEmailException extends Exception {
}
function validateEmail(string $email): void {
if (strpos($email, '@') === false) {
throw new InvalidEmailException("Invalid email");
}
echo "Valid\n";
}
try {
validateEmail("bad");
} catch (InvalidEmailException $e) {
echo $e->getMessage() . "\n";
}
Test yourself
-
How is a custom exception class defined?
- class MyError implements Exception {}
- class MyError inherits Exception {}
- class MyError extends Exception {}
- class MyError uses Exception {}
Show answer
class MyError extends Exception {} — Correct. A subclass is created with extends Exception.
-
Complete the class declaration
<?php class InvalidEmailException ____ { public function text(): string { return $this->getMessage(); } }Show answer
<?php class InvalidEmailException extends Exception { public function text(): string { return $this->getMessage(); } } -
Match the custom exception concepts
- extends Exception
- Derives the class
- parent::__construct()
- Calls the parent constructor
- throw new InvalidEmailException()
- Throws the custom exception
- catch (InvalidEmailException $e)
- Catches the custom exception