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();
}
开发者_JS百科
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
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
}
精彩评论