Different types of exceptions in php

In this article we will see how to use exception subclasses in PHP.


RuntimeException

When an error occurred during the code execution.

A usual case scenario is when there’s a mistake during a database connection; we throw a runtime exception because the failure only occurs when we run the code :


LogicException

When your code is trying to do something illogical.

You have a LogicException when there’s a logic-related error in your code. For exemple we can’t accelerate a car if the engine is not started :


OutOfBoundsException

When the key you’re looking for is invalid.

An OutOfBoundsException occurs when a key is invalid. Let’s say we have a container to store objects:


InvalidArgumentException

When the argument you have provided is invalid.

Let’s say we have a bank account, in PHP we can’t check if an argument is an integer, so we have to do some validation :

Now, we can provide an integer only to the credit() method :

https://gist.github.com/julesbou/0c859273b40f77b68127


ErrorException

When there was an error.

This exception can be used to register an error handler that converts errors to exceptions :


BadMethodCallException

When the method you’re trying to call is invalid.

In Doctrine there is a repository to fetch objects from your database. You can call methods like findOneBySlug(‘php-exceptions’). Doctrine makes a good usage of this method in the EntityRepository:

¯\_(ツ)_/¯

Thanks for reading.

Like what you read? Give Jules a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.