Web Development & WordPress

How to use Try, Catch, Finally : Exceptions in PHP

Suppose you are creating Participants Class where only participants of age 12 are eligible. So you have to use Try, Catch and Finally(optional) to throw exception if age is greater than 12 or less than 12. Here is an example which you can see.


class Participants
{
    public $name;
    public $age;
    function  __construct($name, $age)
    {
        $this->name = $name;
        if ($age == 12) {
            $this->age = $age;
            throw new Exception("Congrats $name You are eligible", 2000);
        } else {
            throw new Exception("Sorry {$name} You are not Eligible to Participate", 1000);
        }
    }
}

try {
    $participant1 = new Participants("Tom", 10);
} catch (Exception $err) {
    echo $err->getCode() . " : " . $err->getMessage();
} finally {
    echo "<br>It runs at the end<br><br>";
}

try {

    $participant2 = new Participants("Jim", 12);
} catch (Exception $err) {
    echo $err->getCode() . " : " . $err->getMessage();
} finally {
    echo "<br>It runs at the end";
}


OUTPUT

1000 : Sorry Tom You are not Eligible to Participate
It runs at the end

2000 : Congrats Jim You are eligible
It runs at the end

Leave a comment