PHP Exception Handling - ErrorException

PHP Exception Handling: InvalidArgumentException

Today in the PHP Exception Handling series, we’ll take a look at one of PHP’s built in exception classes. Specifically, we’re looking at InvalidArgumentException, what it means, and when it’s most useful! Built in exceptions like this one help make PHP exception handling a breeze! Let’s get to it…

The Technical Rundown:

  • All SPL exceptions extend either LogicException or RuntimeException. InvalidArgumentException extends LogicException.
  • InvalidArgumentException is thrown when the provided argument is not of the expected type. (sounds about right)

When Should You Use it?

The InvalidArgumentException is optimal for…well…validating arguments. To learn when this might be useful, take a look the function below – doubleInt().

Simple enough! Pass doubleInt() an integer, and it will return that integer multiplied by two. So, if we run doubleInt(3) like on line 8 above, our output will be the integer 6.

But what happens if we do something like this?

Unfortunately, as you know, this would not output two kittens, (Don’t worry, I’m nearly done with my doubleKitten() function). The string “kitten” doesn’t multiply nicely in PHP, so what we end up with is an output of 0.

Not only is this output totally not useful, but we aren’t notified that anything has gone wrong. PHP simply gives us the output of zero and moves along. Here’s where InvalidArgumentException comes in.

Now that we’ve got a check built in to see if $int is, in fact, an integer, we’re in business. If $int is not an integer, InvalidArgumentException will throw us the error message we determine as part of the exception. In the case of the “kitten” argument:

Fatal error: Uncaught exception 'InvalidArgumentException' with message 'doubleInt expects an integer. Input was: kitten - not an integer.'

With this exception, we’ve now been informed that something happened that wasn’t quite right. In the case of of user input, this is useful because we can now suggest the user submit the correct data type.

And that’s it! InvalidArgumentException is a simple and elegant way to catch arguments of an incorrect data type. On its own, InvalidArgumentException is useful on small projects, but for larger projects you might consider Airbrake’s PHP bug tracker!