What is the difference between Exception, InvalidArgumentException or UnexpectedValueException?

When should I use an Exception, InvalidArgumentException, or UnexpectedValueException?

I do not know the real differences between the two, as I have always used Exception.

+5
source share
1 answer

Various exceptions just give you more granularity and control over how you catch and handle exceptions.

Consider a class in which you do a lot of things - for example. getting input, checking input, and then saving it somewhere. You may decide that if an invalid or empty argument is passed to the get() method, you can throw an InvalidArgumentException . When checking if something is unusual or does not match, you can throw an UnexpectedValueException . If something completely unexpected happens, you can throw a standard Exception .

This becomes useful when you catch, because you can handle different types of exceptions in different ways. For instance:

 class Example { public function get($requiredVar = '') { if (empty($requiredVar)) { throw new InvalidArgumentException('Required var is empty.'); } $this->validate($requiredVar); return $this->process($requiredVar); } public function validate($var = '') { if (strlen($var) !== 12) { throw new UnexpectedValueException('Var should be 12 characters long.'); } return true; } public function process($var) { // ... do something. Assuming it fails, an Exception is thrown throw new Exception('Something unexpected happened'); } } 

In the above class example, when called, it can catch using several types of exceptions:

 try { $example = new Example; $example->get('hello world'); } catch (InvalidArgumentException $e) { var_dump('You forgot to pass a parameter! Exception: ' . $e->getMessage()); } catch (UnexpectedValueException $e) { var_dump('The value you passed didn\'t match the schema... Exception: ' . $e->getMessage()); } catch (Exception $e) { var_dump('Something went wrong... Message: ' . $e->getMessage()); } 

In this case, you will receive an UnexpectedValueException as follows: string(92) "The value you passed didn't match the schema... Exception: Var should be 12 characters long." .

It should also be noted that all these exception classes all the same end with Exception , so if you do not define special handlers for InvalidArgumentException or others, then they will be caught by Exception traps in any case. So why not use them?

+9
source

All Articles