Custom exception classes allow developers to define specialized error types in PHP. By extending the built-in Exception class, you gain better control, cleaner code structure, and more meaningful error handling.
Exception classA custom exception is created using the class keyword and the extends Exception syntax. You can define custom methods to enhance error messages or behaviors.
// Define a custom exception class
<?php
class MyCustomException extends Exception {
public function errorMessage() {
// Build and return a detailed error message
return "Error on line " . $this->getLine() . ": " . $this->getMessage();
}
}
// Throw and catch the custom exception
try {
throw new MyCustomException("Something went wrong!");
}
catch (MyCustomException $e) {
echo $e->errorMessage();
}
?>
The custom exception generates a readable message showing the exact line number and the error description, making debugging much easier.
Exception Flow
DatabaseException