3

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.');
    }
}
}
fabio
  • 2,269
  • 5
  • 22
  • 34
  • 1
    class `Email` extends `String`??? – Jon Feb 12 '11 at 19:18
  • @Jon: That's a weird superclass name, but it's legal: there is no built-in `String` class in PHP. – BoltClock Feb 12 '11 at 19:18
  • it's just a silly example. Pretend that String is some kind of ValueObject or something. – fabio Feb 12 '11 at 19:19
  • 3
    @BoltClock: I know. But an email IS-NOT-A string... – Jon Feb 12 '11 at 19:24
  • @Jon: But it can be represented as a string, no? – fabio Feb 12 '11 at 19:26
  • @fabio: The email's subject line can; its recipient list can; its body can; etc etc. But the email as a whole cannot be, unless you are willing to delimit each one of those "fields" with a magic sequence, escape that sequence wherever it appears inside the fields, etc. And what's more, when modeling something as a class, you are not supposed to derive from a base unless you represent an object of that base. An email can be serialized as a string, but it *is* not one. – Jon Feb 12 '11 at 19:29
  • @Jon: I guess he meant `EmailAddress` or something as opposed to an email message. – BoltClock Feb 12 '11 at 19:33
  • 1
    @BoltClock: Could be. Anyway, the comment was intended as an aside, so I think it's gone on too long already. – Jon Feb 12 '11 at 19:36

1 Answers1

11

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.');
    }
}
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356