views:

45

answers:

1

Hello all,

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

+11  A: 

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
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
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 againMEM
MEM
`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
Thanks. :)"getCode and getMessage will work" - ok. But how will they be related with $codigo, $result->msg previously passed as throw arguments?
MEM
@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
Ok. ;) Let's go there.Thanks for the add on Daniel, now I better understand an advantage of using custom Exception names.
MEM