Course of Raku / Objects, I/O, and exceptions / Exceptions / Custom exceptions / Exercises / Too big
Solution: Too big
Here is a possible solution to the task.
Code
class TooBig is Exception {
has $.value;
has $.limit;
method message {
"Value $.value exceeds the limit of $.limit";
}
}
my $limit = 50;
for 30, 99, 60 -> $value {
TooBig.new(value => $value, limit => $limit).throw if $value > $limit;
say "Value $value is within the limit";
CATCH {
when TooBig {
say .message;
say "Try a value up to {.limit}.";
}
}
}🦋 You can find the source code in the file too-big.raku.
Output
Value 30 is within the limit
Value 99 exceeds the limit of 50
Try a value up to 50.
Value 60 exceeds the limit of 50
Try a value up to 50.Comments
TooBig is Exceptionmakes the class a throwable exception. It carries two pieces of data,valueandlimit, and itsmessagemethod weaves both into the reported text..throwraises the exception, andwhen TooBigmatches it by type. The handler does more than print the message: it reads thelimitattribute straight off the caught object to give a helpful hint. That is the advantage of a custom exception over a plain string — the handler receives structured data it can act on.The exception is thrown only when
$value > $limit. For30, no exception is raised and the loop body runs to itssay, printing that the value is within the limit. For99and60, thethrowfires, so thatsayis skipped and theCATCHhandles it instead. Theforbody is itself the block theCATCHguards, so a caught exception ends only the current iteration — the loop then simply moves on to the next value.
Course navigation
← Too big | A negative error →