How to Handle InvalidArgument Exception in PHP

How to Handle InvalidArgument Exception in PHP
Table of Contents

The PHP InvalidArgumentException is an exception that is thrown when an inappropriate argument is passed to a function. This could be because of an unexpected data type or invalid data.

What Causes InvalidArgumentException

There are mainly two cases where an InvalidArgumentException can be thrown:

  • When the strict_types flag is enabled and an unexpected data type is passed for an argument.
  • When the data type of an argument is correct, but the data value is invalid.

InvalidArgumentException Example

Hereโ€™s an example of an InvalidArgumentException thrown when an inappropriate type is passed as an argument:

<?php

declare(strict_types=1);

function multiply($x, $y)
{
  if(!is_numeric($x) || !is_numeric($y)) {
    throw new InvalidArgumentException('Both arguments must be numbers');
  }
  return $x * $y;
}

$res = multiply('Hello', 'World');

?>

In the above example, the multiply() function expects two numbers as arguments. If either of the two arguments are not numbers, an InvalidArgumentException is thrown:

PHP Fatal error:  Uncaught InvalidArgumentException: Both arguments must be numbers in main.php:8
Stack trace:
#0 main.php(13): multiply()
#1 {main}
  thrown in main.php on line 8
  

How to Handle InvalidArgumentException in PHP

The following steps should be followed to handle an InvalidArgumentException:

  1. Inspect the exception stack trace and identify the lines of code that pass the invalid argument.
  2. Update the code to make sure that the passed argument is valid within the method that uses it.
  3. To catch the InvalidArgumentException, try-catch blocks can be used. Certain situations can be handled using a try-catch block such as asking for user input again instead of stopping execution when an invalid argument is encountered.

Track, Analyze and Manage Errors With Rollbar

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing PHP errors easier than ever. Try it today!

Related Resources

Build with confidence. Release with clarity.

Rollbar helps you track what breaks, understand why, and improve what comes next.

โœ“ 5K free events per month, forever
โœ“ 14-day full feature trial
โœ“ Easy and quick installation
Get started in minutes

Plans starting at $0. Take off with our 14-day full feature Free Trial.