3

I'm trying to work with exceptions.

So I have something like:

If something bad occurs:

throw new CreateContactException($codigo, $result->msg);

Later on, I will, try and if not ok, catch:

try 
{
  createContact();
}
catch(CreateContactException $e) 
{
  $error .= 'An error occurred with the code:'.$e->getCode().' and message:'.$e->getMessage();
}

1) Will this work? I mean, this getCode() and getMessage() aren't related with the CreateContactException arguments are they?

2) Must I have, somewhere, a CreateContactException class that extends Exception? I mean, can we have custom names for our exceptions without the need of creating an extended class?

Thanks a lot in advance, MEM

MEM
  • 30,529
  • 42
  • 121
  • 191

1 Answers1

12

Exceptions must just be subclasses of the built-in Exception class, so you can create a new one like this:

class CreateContactException extends Exception {}

Trying to throw other classes as exceptions will result in an error.

An advantage using different names is that you can have multiple catch blocks, so you can catch different kinds of exceptions and let others slip through:

try {
    // do something
}
catch (CreateContactException $e) {
    // handle this
}
catch (DomainException $e) {
    // handle this
}
Daniel Egeberg
  • 8,359
  • 31
  • 44
  • Ok. So that will be the first thing to do. Create a class that extends Exception. If it will be empty, why not just use Exception instead ? – MEM Jul 29 '10 at 10:43
  • Supposing we have that class created, how can we relate getCode and getMessage with our throw arguments? I'm a bit lost I realise that... Thanks again MEM – MEM Jul 29 '10 at 10:45
  • 1
    `why not just use Exception instead` Because you want to be more specific and be able to throw and catch specific exception types. Since it extends Exception it inherits all the methods Exception has, so getCode and getMessage will work. – Mchl Jul 29 '10 at 10:48
  • Thanks. :) "getCode and getMessage will work" - ok. But how will they be related with $codigo, $result->msg previously passed as throw arguments? – MEM Jul 29 '10 at 10:50
  • @MEM, Refer to the documentation: http://us2.php.net/manual/en/language.exceptions.extending.php http://us2.php.net/manual/en/class.exception.php – strager Jul 29 '10 at 10:53
  • Ok. ;) Let's go there. Thanks for the add on Daniel, now I better understand an advantage of using custom Exception names. – MEM Jul 29 '10 at 11:02