Custom exception classes help you create your own error types. This makes it easier to find and fix specific problems in your code.
0
0
Custom exception classes in PHP
Introduction
When you want to handle different errors in different ways.
When you want to add extra information to an error.
When you want to group related errors together.
When you want clearer error messages for your users.
When you want to separate your error handling from built-in PHP errors.
Syntax
PHP
<?php class MyCustomException extends Exception { // You can add custom properties or methods here }
Custom exceptions extend the built-in Exception class.
You can add your own methods or properties to provide more details about the error.
Examples
This creates a simple custom exception named
FileNotFoundException.PHP
<?php class FileNotFoundException extends Exception {}
This custom exception stores which form field caused the validation error.
PHP
<?php class ValidationException extends Exception { private string $field; public function __construct(string $message, string $field) { parent::__construct($message); $this->field = $field; } public function getField(): string { return $this->field; } }
Sample Program
This program defines a custom exception AgeException. The function checkAge throws this exception if the age is less than 18. The try-catch block catches the custom exception and prints a message.
PHP
<?php class AgeException extends Exception {} function checkAge(int $age) { if ($age < 18) { throw new AgeException("Age must be 18 or older."); } echo "Age is valid: $age\n"; } try { checkAge(15); } catch (AgeException $e) { echo "Caught custom exception: " . $e->getMessage() . "\n"; }
OutputSuccess
Important Notes
Always extend the built-in Exception class when creating custom exceptions.
Use try-catch blocks to handle your custom exceptions gracefully.
Custom exceptions help keep your error handling organized and clear.
Summary
Custom exceptions let you create specific error types for your code.
They extend the built-in Exception class.
Use them with try-catch to handle errors clearly and safely.