PHP Exception Handling - ErrorException

PHP Exception Handling – OutOfBoundsException

Making our way through our detailed PHP Exception Handling series, today we come to the OutOfBoundsException. The OutOfBoundsException is not to be confused with the OutOfRangeException, which we covered a few weeks ago in our PHP Exception Handling - OutOfRangeException article. While OutOfRangeException is meant to be used at compile time, the OutOfBoundsException inherits directly from the RuntimeException and, thus, it is used for key-based errors that occur during runtime.

We’ll start this article by looking at where the OutOfBoundsException fits into the larger PHP Exception Hierarchy. Then, we’ll explore some functional code samples that illustrate how the OutOfBoundsException is typically thrown, or is simply meant to be used, so let’s get going!

The Technical Rundown

All PHP errors implement the Throwable interface, or are extended from another inherited class therein. The full exception hierarchy of this error is:

Full Code Sample

Below is the full code sample we’ll be using in this article. Feel free to use any or all of the code if you wish to follow along.

When Should You Use It?

The official documentation states that the OutOfBoundsException “represents errors that cannot be detected at compile time.” In effect, this means it is ideal for errors that are not caused by a logical issue, but instead are due to invalid data that appears during runtime. For example, a database that retrieves a value that is used elsewhere in the code could produce an OutOfBoundsException, since that particular value may be invalid or “outside of the bounds” of what is allowed.

To illustrate this principle, we’re expanding a bit on our trusty Book class by adding a characters property, which holds a series of Character class instances that represent some of the primary characters within the Book. For our example, we’ll be creating and retrieving Characters directly in the code, but this data could just as easily come from a third-party, such as a database or service API. Regardless, we can use this example to illustrate how, in some situations, we need to plan for attempts to access data that doesn’t exist in a data set, and to respond at runtime with an appropriate OutOfBoundsException.

We begin with the new Character class:

Nothing fancy going on here. We just need to track the Character's name and (optional) biography.

Now we need a way to add Characters to a Book instance. We accomplish this by adding four new methods to the Book class:

The addCharacter(Character $character, $key = null) method adds a new Character, either to the end of the array or to the specified $key. getCharacter($key) retrieves the Character element at the specified $key. However, we don’t know at compile time whether the passed $key will be valid or not, so we need to check if it exists in the characters collection property. If not, we throw a new OutOfBoundsException informing the user of the issue. Finally, getCharacters() and setCharacters(array $characters) are the standard property getter and setter methods.

Now, let’s test this out to make sure everything works as expected. The executeExamples() method contains all our test code, including the try-catch block to handle any expected OutOfBoundsExceptions:

We start by creating a new Book representing A Game of Thrones. Next, we create a trio of Characters representing three main characters in the book, then call $book->addCharacter(Character $character, $key = null) to add them all. Just to confirm we can manually specify a $key argument, we passed 'tyrion' as the $key parameter for his entry. After that, we output the $book instance to the log to see that everything has been added as expected:

Everything looks just right! Now, let’s see what happens if we call $book->GetCharacter('tyrone'), which represents an invalid $key within the characters array property:

Just as intended, an OutOfBoundsException is thrown, indicating a Character element at the key 'tyrone' doesn’t exist.

Check out the Airbrake-PHP library, designed to quickly and easily integrate into any PHP project, giving you and your team access to real-time error monitoring and reporting throughout your application’s entire life cycle. With automatic, instantaneous error and exception notifications at your fingertips, you’ll be constantly aware of your application’s health, including any issues that may arise. Best of all, with Airbrake’s robust web dashboard cataloging every error that occurs, you and your team can immediately dive into the exact details of what went wrong, making it easy to quickly recognize and resolve problems.