Should I rethrow an exception in this case?

3.8k Views Asked by At

Is this approach ok? Am I handling exceptions correctly? See my class:

class Email extends String
{
protected function validate($email)
{
    try{
        parent::validate($email);
    } catch(InvalidArgumentException $e) {
        throw $e;
    }

    if(!filter_var($value,FILTER_VALIDATE_EMAIL))
    {
        throw new InvalidArgumentException('etc.');
    }
}
}
1

There are 1 best solutions below

2
On BEST ANSWER

If you are not going to do anything with the exception within that catch block, it's not necessary to enclose that parent method call in its own try-catch block. The method will automatically pass the exception up from the parent's implementation if it encounters one outside a try-catch block, just like if you threw an exception from the same context (as you do after your if condition):

protected function validate($email)
{
    parent::validate($email);

    if (!filter_var($value, FILTER_VALIDATE_EMAIL))
    {
        throw new InvalidArgumentException('etc.');
    }
}