I'm studying error handling in PHP, and I already know how to use Exception
, but I was in doubt about LogicException
, what is the purpose of it? And how to use it correctly?
I'm studying error handling in PHP, and I already know how to use Exception
, but I was in doubt about LogicException
, what is the purpose of it? And how to use it correctly?
LogicException
according to the PHP documentation, it is an exception type related to some error of logic in your application, which will involve a change in your code.
In other words, it would be the errors where "Huuum ... this should not have happened."
Example
I could not think of a more elaborate real situation, but in this case the implementation is working
<?php
Class Divisao
{
private $divisor;
private $dividendo;
public function __construct($dividendo, $divisor){
$this->dividendo = (int) $dividendo;
$this->divisor = (int) $divisor;
}
private function valida(){
// @todo Verifica se o Divisor é Igual a 0
return true;
}
public function dividir(){
if ($this->valida()){
// Se mesmo depois da validação o divisor for Zero, temos um erro de lógica.
if ($this->divisor === 0) throw new LogicException('Validação Falhou');
return $this->dividendo / $this->divisor;
}
}
}
try {
$d1 = new Divisao(2,2);
$d2 = new Divisao(2,0);
echo $d1->dividir();
echo $d2->dividir();
} catch (LogicException $e) {
echo "Erro de Lógica " . $e->getMessage();
}
The exception LogicException
is thrown when the code has some logic error.
/ p>
Exception representing error in program logic. This kind of exception should lead directly to a fix in your code.
Using LogicException
is similar to DomainException
, it should be used if your code produces a value it should not produce.
The exception
DomainException
is thrown when a value does not adhere to a valid data domain defined.
Example:
function diaUtil($dia){
switch ($dia){
case 2: echo "Segunda-feira"; break;
case 3: echo "Terça-feira"; break;
case 4: echo "Quarta-feira"; break;
case 5: echo "Quinta-feira"; break;
case 6: echo "Sexta-Feira"; break;
default:
throw new DomainException("Não é um dia útil válido");
}
}
diaUtil(3); // Terça-feira
diaUtil(10); // Não é um dia útil válido
Hierarchy:
LogicException
(extension of Exception
)
RuntimeException
(extension of Exception
)