开发者

newbie: throw new exception - can we change exception name?

开发者 https://www.devze.com 2023-01-09 14:54 出处:网络
I\'m trying to work with exceptions. So I have something like: If something bad occurs: throw new CreateContactException($codigo, $result->msg);

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
}
0

精彩评论

暂无评论...
验证码 换一张
取 消