Stop using regular exceptions in PHP!


  • Introduction
  • What’re Exceptions mean?
  • Exceptions methods
  • Throwing an Exception
  • Subclassing Exception
  • Reasons why you might want to use subclass exception
  • Example
  • Full Example
  • Conclusion


You might be wondering why I should stop using exceptions in PHP! well, to clarify in this tutorial will see two examples of using exceptions (regular - custom), also will see the advantages of using custom exceptions, finally, I made an example on GitHub to help you start using custom exceptions, I’ll update this example in future, to be more complex to simulates real projects examples.

What’re Exceptions mean?

PHP 5 introduced exceptions to PHP, a radically different way of handling error conditions. Different for PHP, that is. You will find them hauntingly familiar if you have Java or C++ experience.

An exception is a special object instantiated from the built-in Exception class (or from a derived class). Objects of type Exception are designed to hold and report error information.

The Exception class constructor accepts two optional arguments, a message string and an error code. The class provides some useful methods for analyzing error conditions.

Exceptions methods

# Get the message string that was passed to the constructor. 
# Get the code integer that was passed to the constructor.
# Get the file in which the exception was generated.
# Get the line number at which the exception was generated
# Get a nested Exception object
# Get a multidimensional array tracing the method calls that led to the exception, including method, class, file, and argument data
# Get a string version of the data returned by getTrace()
# Called automatically when the Exception object is used in string context. Returns a string describing the exception details

Throwing an Exception

The throw keyword is used in conjunction with an Exception object. It halts the execution of the current method and passes responsibility for handling the error back to the calling code

So how does client code know how to handle an exception when thrown?

When you invoke a method that may throw an exception, you can wrap your call in a try clause. A try clause is made up of the try keyword followed by braces. The try clause must be followed by at least one catch clause in which you can handle any error, like this:

try { 
// code
} catch (\Exception $e) {

As you can see, the catch clause superficially resembles a method declaration. When an exception is thrown, the catch clause in the invoking scope is called. The Exception object is automatically passed in as the argument variable.

just as execution is halted within the throwing method when an exception is thrown, so it is within the
try clause — control passes directly to the catch clause.

Subclassing Exception

You can create classes that extend the Exception class as you would with any user-defined class.

Reasons why you might want to use subclass exception

  • You can extend the class’s functionality.
  • The fact that a derived class defines a new class type can aid error handling in itself.
  • Clean and readable code.
  • Easy to understand and also easy to remember if you stop working on the project and after a while when back to the project it’ll be easy to understand what each class/method of exception does (if you name your exception classes and methods well).


class IsUser extends Exception
public static function notAllowed($user)
return new static('Can not delete the user' . $user->name);

We’ve created a regular class IsUser that extends the native Exception class. Next, the class has the static method notAllowed which upon called will return the exception as shown in the code.

This can be used like so.

public function delete() 
// we use it here
if (!$user->isAllowed) {
throw IsUser::notAllowed($user)

As you can see, the code is now less cluttered and the code doesn’t contain the exception messages here and there. Also, if you name your exception classes and methods well, you could just guess the purpose of the exceptions by just looking at these names.

Full Example

I made a repository on GitHub to help you with how you can use custom exceptions in PHP, also I made unit tests to test the custom exception class.
please check it from here


Exceptions are really useful when you want to handle some situations which can not be handled gracefully otherwise. So, using exceptions, you can handle certain scenarios by showing a nice error message also the code will be less cluttered and doesn’t contain the exception message here and there.

Let’s connect on LinkedIn, Twitter




Software engineer, Problem solver, Geek.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Algorithms and Data Structures Part VII

Software engineering practices to improve management

Terraform — Securing your State file

Connecting to AWS EC2 Instance Using Putty from Windows

File Cards Mac App REVIEW

Adulthood can otherwise be an advantage in starting a software development career.

Getting started with Ansible

Performance and Load Testing with JMeter for beginners

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store


Software engineer, Problem solver, Geek.

More from Medium

Risky Nested MySQL Queries in PHP Loop

Risky Nested queries inside loop in PHP

The dd() function in each PHP project

Should you try Kotlin as a PHP developer?

Refactoring #5: From arrays to Data Transfer Objects