throw new Exception. Catch and echo the message.
Goal
Catch a thrown Exception.
<?php
try {
throw new Exception("empty till");
} catch (Exception $e) {
echo $e->getMessage(), PHP_EOL;
}<?php
function needCity($city) {
if ($city === "") {
throw new Exception("city required");
}
return $city;
}
try {
echo needCity("Nairobi"), PHP_EOL;
echo needCity(""), PHP_EOL;
} catch (Exception $e) {
echo "caught ", $e->getMessage(), PHP_EOL;
}<?php
try {
json_decode("{", true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
echo "bad json", PHP_EOL;
}<?php
echo gettype(new Exception("x")), PHP_EOL;