Creating a Custom Exception
Part of the Logic & Flow section of Coddy's PHP journey — lesson 56 of 68.
While PHP's built-in Exception class works well for general error handling, creating your own custom exception classes provides much more specific and meaningful error messages. Custom exceptions help you distinguish between different types of problems in your code and handle them appropriately.
To create a custom exception, you extend PHP's base Exception class using the extends keyword. This inheritance gives your custom exception all the functionality of the standard exception while allowing you to add your own specific behavior or simply provide a more descriptive name.
<?php
class InvalidEmailException extends Exception {
// The class can be empty - it inherits everything from Exception
}
// You can also add custom properties or methods
class CustomException extends Exception {
public function getCustomMessage() {
return "Custom error: " . $this->getMessage();
}
}
?>The power of custom exceptions lies in their descriptive names and the ability to catch specific exception types. Instead of catching a generic Exception, you can catch InvalidEmailException, DatabaseConnectionException, or any other custom exception you create. This makes your error handling more precise and your code more maintainable.
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 one input: a string representing an exception class name. This input will be a single word that should be used as the name for your custom exception class (example: NegativeBalanceException or InvalidUsernameException).
Read the input and create a custom exception class using the provided name. Your custom exception class should extend PHP's base Exception class. After creating the class, print "Custom exception created: " followed by the class name you received as input.
Input format: One line containing a string representing the exception class name (example: InvalidAgeException)
Expected output: Custom exception created: followed by the exception class name
Cheat sheet
To create custom exceptions in PHP, extend the base Exception class using the extends keyword:
<?php
class InvalidEmailException extends Exception {
// The class can be empty - it inherits everything from Exception
}
// You can also add custom properties or methods
class CustomException extends Exception {
public function getCustomMessage() {
return "Custom error: " . $this->getMessage();
}
}
?>Custom exceptions provide more specific and meaningful error messages, allowing you to catch specific exception types instead of generic Exception objects. This makes error handling more precise and code more maintainable.
Try it yourself
<?php
// Read the exception class name
$className = trim(fgets(STDIN));
// TODO: Write your code below to create the custom exception class
// Output the result
echo "Custom exception created: " . $className;
?>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