Using a Custom Exception
Part of the Logic & Flow section of Coddy's PHP journey — lesson 57 of 68.
Now that you've created your own custom exception class, it's time to put it to practical use. Using a custom exception involves two key steps: throwing your specific exception type when a problem occurs, and catching that specific exception type to handle it appropriately.
When you throw a custom exception, you use the same throw keyword but create an instance of your custom class instead of the generic Exception class. This makes your error handling more precise and meaningful.
<?php
class InvalidEmailException extends Exception {}
function validateEmail($email) {
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
throw new InvalidEmailException("Invalid email format: " . $email);
}
echo "Email is valid!";
}
?>The real power comes when catching your custom exception. Instead of catching a generic Exception, you can catch your specific InvalidEmailException. This allows you to handle different types of errors in different ways, making your error handling more targeted and informative.
<?php
try {
validateEmail("invalid-email");
} catch (InvalidEmailException $e) {
echo "Email error: " . $e->getMessage();
}
?>This approach gives you precise control over error handling, allowing you to respond differently to various types of problems in your application.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
Challenge
EasyYou will receive three inputs: a username string, a password string, and a minimum password length number. The username should not be empty, and the password should meet the minimum length requirement.
Create a custom exception class called InvalidCredentialsException that extends the base Exception class.
Create a function called validateCredentials that accepts three parameters: username, password, and minimum length. Inside this function:
- If the username is empty (an empty string), throw an
InvalidCredentialsExceptionwith the message"Username cannot be empty" - If the password length is less than the minimum length, throw an
InvalidCredentialsExceptionwith the message"Password must be at least X characters long"(where X is the minimum length value) - If both validations pass, print
"Credentials are valid"
Use a try...catch block to call the function with the provided inputs. In the catch block, catch the InvalidCredentialsException specifically and print "Validation error: " followed by the exception message using the getMessage() method.
Input format:
- First line: A string representing the username (example:
john_doeor an empty string) - Second line: A string representing the password (example:
pass123) - Third line: An integer representing the minimum password length (example:
8)
Expected output:
- If credentials are valid:
Credentials are valid - If username is empty:
Validation error: Username cannot be empty - If password is too short:
Validation error: Password must be at least X characters long(where X is the minimum length)
Cheat sheet
To use custom exceptions, throw an instance of your custom class and catch that specific exception type:
<?php
class InvalidEmailException extends Exception {}
function validateEmail($email) {
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
throw new InvalidEmailException("Invalid email format: " . $email);
}
echo "Email is valid!";
}
try {
validateEmail("invalid-email");
} catch (InvalidEmailException $e) {
echo "Email error: " . $e->getMessage();
}
?>This allows for precise error handling by catching specific exception types rather than generic Exception objects.
Try it yourself
<?php
// Read input
$username = trim(fgets(STDIN));
$password = trim(fgets(STDIN));
$minLength = intval(fgets(STDIN));
// TODO: Write your code below
// 1. Create the InvalidCredentialsException class
// 2. Create the validateCredentials function
// 3. Use try...catch block to call the function and handle exceptions
?>This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Advanced Functions
Anonymous FunctionsClosures and 'use'Arrow FunctionsCallback FunctionsUsing 'call_user_func'Variable FunctionsPassing by ReferenceRecursive FunctionsRecap: Function Medley4Multi-dimensional Arrays
Creating a 2D ArrayAccessing 2D Array ElementsModifying 2D Array ElementsIterating with Nested Loops2D Associative ArraysRecap: Simple Grid Exercise2Advanced Array Manipulations
Adding with 'array_push'Removing with 'array_pop'Adding with 'array_unshift'Removing with 'array_shift'Merging Indexed ArraysMerging Associative ArraysExtracting with 'array_slice'Values with 'in_array'Keys with 'array_search'Recap: Playlist Exercise5Student Gradebook
Project Setup: Data StructureAdding a New StudentAdding a Grade to a StudentCalculating Student's AverageFinding the Top StudentGenerating a Report Card8Error and Exception Handling
Understanding PHP ErrorsThe 'try...catch' BlockThe 'finally' BlockThrowing an ExceptionCreating a Custom ExceptionUsing a Custom ExceptionRecap: Input Validation3Sorting Arrays
Sort Indexed Arrays AscendingSort Indexed Arrays DescendingSort Assoc Arrays by ValueSort Assoc Arrays by KeyNatural Order SortingCustom Sorting with 'usort'Recap: Leaderboard Sorting