Ad space (banner)
๐Ÿ˜PHP Lessons
Lesson 25 / 68

Writing a Custom Exception Class

In this lesson you will learn how to define a custom exception class in PHP so error types are easy to tell apart. This is for anyone searching for "PHP custom exception how to create".

Inheriting from Exception gives you an exception of your own. Naming a class per kind of failure makes it much easier to tell what went wrong when you catch it. Once you can distinguish "invalid input" from "network failure", you can write a response suited to each.

The sample code creates a custom exception with the simple, empty declaration class ValidationError extends Exception {}. It raises it with throw new ValidationError(...) inside checkAge when the age is invalid, and catches it with catch (ValidationError $e).

A common stumbling block for beginners is not knowing what to put inside a custom exception class. In fact an empty declaration works perfectly well - inheriting from Exception is enough. Giving it a name to distinguish it is the main point.

Giving an exception a previous property lets it carry the details of the original underlying failure along with it. The larger the application, the more the design of these custom exception classes matters.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run PHP directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)