Error Handling
throw new SomeException("message") raises an exception; a try block around code that might throw is followed by one or more catch (ExceptionType $e) blocks, matched in order against the exception's actual class, and an optional finally block that runs whether or not anything was thrown — including when a catch block itself returns. PHP ships a set of built-in exception classes for common cases (InvalidArgumentException, RuntimeException, and others) rather than making every project invent its own from scratch for the ordinary cases.
<?php
function divide($a, $b) {
if ($b === 0) {
throw new InvalidArgumentException("Cannot divide by zero");
}
return $a / $b;
}
try {
echo divide(10, 2), "\n";
echo divide(10, 0), "\n";
} catch (InvalidArgumentException $e) {
echo "Caught: " . $e->getMessage() . "\n";
} finally {
echo "Done.\n";
}
5 Caught: Cannot divide by zero Done.
divide(10, 2) returned 5 normally, with the try block not yet interrupted; divide(10, 0) threw, which immediately stopped the try block (the second echo's own "\n" never printed) and jumped straight to the matching catch, where $e->getMessage() recovered the exact message the exception was constructed with. finally's "Done.\n" printed regardless — that's the whole point of finally — whether the preceding code had thrown or not.
That closes this course. You've gone from $variable and echo through PHP's two defining structural choices — the associative array as its one workhorse collection, and the loose/strict (==/===) equality split verified live on this site's own PHP 7.4.1 runtime rather than taken on faith — through functions, closures, and a full object model with classes, visibility, inheritance, interfaces, and traits, to exception handling. Every code block in every lesson actually ran, on a real interpreter, exactly as shown. The rest is building things with it.
Practice exercise
Write safeDivide($a, $b) that throws new InvalidArgumentException("division by zero") when $b === 0, otherwise returns $a / $b — call safeDivide(10, 0) inside a try/catch and echo "Error: " followed by the caught exception's message.