Question

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.');
    }
}
}
Was it helpful?

Solution

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.');
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top