7
In PHP, we have several types of exceptions that can be released. Among them:
BadFunctionCallException
BadMethodCallException
DomainException
InvalidArgumentException
LengthException
LogicException
OutOfBoundsException
OutOfRangeException
OverflowException
RangeException
RuntimeException
UnderflowException
UnexpectedValueException
The only one I really know to be different is ErrorException
, allowing the exception to be made according to the data captured by set_error_handler
.
However, as for the others, sometimes I feel a little confused about which to use.
For example:
function teste($int, array $array){
if (! is_int($int)) {
// lanço minha exceção aqui por que o número não é do tipo INT
}
array_push($array, $int);
return $array;
}
I should cast what exception?
InvalidArgumentException
,UnexpectedValueException
orBadFunctionCallException
?Is there a defined pattern (a PSR or something like that) where it explains when to use each one?
Reference PHP Handbook: Exceptions
I didn’t understand the -1 :(
– Wallace Maxters
If PHP allowed it hinting type with primitive types, you wouldn’t even have to worry about that
</rant>
. But given your example, I think we should useInvalidArgumentException
.– bfavaretto
Now comes the question that tingles the brain: And when should I use
UnexpcetedValueException
andBadFunctionCallException
?– Wallace Maxters
I’m trying to answer that. I do not know if the intention is to have description p/ all, I do not know if this would not leave the answer too long, especially if we take into account that the documentation is clear in all of them.
– Maniero
It is important to remember that the exceptions follow a hierarchy: http://php.net/manual/en/spl.exceptions.php#spl.exceptions.Tree
– gmsantos
But, as you always say, documentation is rubbish!
– Wallace Maxters
Being a trash doesn’t mean she should be ignored.
– Maniero
kkkkkkkkkkkkkkkkkkkkk, ok
– Wallace Maxters