Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / PHP

LogicException

LogicException represents a defect in the program’s use of an object or an invariant violation.

Version: PHP 8.4; repository runtime, production runtime not attested

Syntax

throw new LogicException("already sealed")

LogicException represents a defect in the program’s use of an object or an invariant violation. Its subclasses include DomainException and InvalidArgumentException, so a catch for the base also handles them. The example accepts the first seal operation and rejects a second call because its precondition has become false. No PHP engine check enforces this domain rule.

class Envelope {
    private bool $sealed = false;
    public function seal(): void {
        if ($this->sealed) { throw new LogicException("already sealed"); }
        $this->sealed = true;
    }
}
$e = new Envelope(); $e->seal();
try { $e->seal(); } catch (LogicException $x) { echo $x->getMessage(), PHP_EOL; }
try { throw new DomainException("range"); } catch (LogicException $x) { echo get_class($x); }
already sealed
DomainException

Examples

<?php
class Envelope {
    private bool $sealed = false;
    public function seal(): void {
        if ($this->sealed) { throw new LogicException("already sealed"); }
        $this->sealed = true;
    }
}
$e = new Envelope(); $e->seal();
try { $e->seal(); } catch (LogicException $x) { echo $x->getMessage(), PHP_EOL; }
try { throw new DomainException("range"); } catch (LogicException $x) { echo get_class($x); }

Result

already sealed
DomainException

Sources