PHP Reference ยท Exceptions and Errors
Custom exceptions in PHP
Design your own PHP exception classes: when to subclass, marker interfaces, named constructors, extra data, chaining with previous and catching by hierarchy.
A custom exception is a class that extends Exception (or one of its SPL children) to give a failure its own name. The name is the point: catch (InsufficientFunds $e) says exactly what the handler deals with, and it lets other failures pass through untouched.
You rarely need to write much. An empty subclass is already useful, and you add behavior only when the exception must carry data, such as the amount that was missing.
class InsufficientFunds extends RuntimeException {}
A small hierarchy
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Named constructors and chaining
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Design guidelines
- Pick the right parent. Extend
RuntimeExceptionfor failures that come from the environment or data,LogicException(orInvalidArgumentException) for misuse of your API. ExtendExceptiononly when neither fits. - One base class per library or module lets callers catch everything from you with a single
catch. A marker interface, as in the first example, does the same without forcing a single parent class. - Name by the problem, not the place.
InsufficientFundsandEmailAlreadyTakenread better thanAccountServiceException. By convention the suffixExceptionis optional; stay consistent within a project. - Carry data in properties, not only in the message. Callers can then react (
$e->missing) without parsing text.readonlyproperties keep them safe. - Keep the standard constructor shape (
$message,$code,$previous) unless you have a reason to change it. If your constructor builds the message, still callparent::__construct()so the base state is set. - Chain, don't replace. When you translate a low-level exception into your own, pass the original as
$previousso the real cause stays in logs. - Order catch blocks from specific to general. PHP uses the first block that matches, so a parent class placed first hides its children.
- Don't use exceptions for expected outcomes such as "no search results"; they are for failures.
- Messages are for developers. Keep user-facing text separate, for example in a method like
userMessage(). - Don't override final methods.
getMessage(),getCode(),getPrevious(),getFile(),getLine()andgetTrace()are final. You can override__toString().