5. Errors
A task with an empty title makes no sense. The constructor throws an error for it:
<?nvs// This program throws an error for a task with an empty title, and catches it.class Task{ public string $title;
public function constructor(string $title) { if ($title == '') { // `throw` stops the method. The caller gets the error. throw new LogicError('a task needs a title'); } $this->title = $title; }}
array<string> $titles = ['Buy milk', ''];foreach ($titles as string $title) { try { var $task = new Task($title); echo 'added: ', $task->title, "\n"; } catch (LogicError $e) { // `$e->message` is the text given to the error. echo 'not added: ', $e->message, "\n"; }}added: Buy milknot added: a task needs a titlethrow stops the method at once. The error goes to the caller, and then to its caller, until a
catch clause takes it.
catch (LogicError $e) takes errors of the class LogicError. The loop then continues with the
next title. Without the try, the program stops at the first error and prints it.
Read more in Syntax: throw and catch and Syntax: error types.
Next: step 6, enums and match.
