Newbie: throw new exception - is it possible to change the name of the exception?

I am trying to work with exceptions.

So, I have something like:

If something is wrong:

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

I'll try later, 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 it work? I mean, getCode () and getMessage () are not related to CreateContactException arguments?

2) Should I have somewhere a CreateContactException class that extends Exception? I mean, can we have custom names for our exceptions without having to create an extended class?

Thank you very much in advance, MEM

+3
source share
1 answer

Exception, , :

class CreateContactException extends Exception {}

.

, , , catch, :

try {
    // do something
}
catch (CreateContactException $e) {
    // handle this
}
catch (DomainException $e) {
    // handle this
}
+12

Source: https://habr.com/ru/post/1757115/


All Articles