Skip to content
Justice Tech School

Exceptions

throw an Exception and catch it with try catch. finally always runs.

Example
function div($a, $b) {
    if ($b == 0) throw new InvalidArgumentException("zero");
    return $a / $b;
}
try { echo div(1, 0); }
catch (InvalidArgumentException $e) { echo "caught ", $e->getMessage(); }
finally { echo "|done"; }

Result

caught zero|done

Exercise

Throw.

 new Exception("x");

Quiz Test

When does finally run?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.