How to use Logicexception from PHP?

Asked

Viewed 134 times

4

I’m studying the handling of errors in PHP, and already know how to use Exception, but I was in doubt about the LogicException, what is its purpose? And how to use it correctly?

2 answers

1

LogicException according to the PHP documentation, it is kind of exception related to some logic error in your application, which will imply a change in your code.

In other words, it would be the mistakes where "Huuum... this shouldn’t have happened".

Example

I couldn’t 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();
}
  • 1

    ok, how would be the implementation of this exception? the same way as the normal Exception? I’ve done this and no result :/

1

The exception LogicException is released when the code shows some logic error.

Exception representing error in program logic. This type of exception must lead directly to a correction in your code.

The use of LogicException is similar to DomainException, it should be used if your code produces a value that should not produce.

The exception DomainException is launched when a value does not adhere to a defined valid data domain.

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

See DEMO

Hierarchy:

inserir descrição da imagem

  1. LogicException (extension of Exception)
  2. RuntimeException (extension of Exception)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.