Creating custom exceptions
In the previous sections, we have seen that exceptions in Perl 6 use the object-oriented approach, which, in particular, helps to distinguish between different exceptions in the CATCH
block.
In this section, we will create a custom exception that is integrated into the Perl 6 system as smoothly as any other built-in classes in the X::
namespace. If you do not have any special requirements, create your custom exception classes in the same namespace.
For example, let us create a Lift
class together with the X::Lift::Overload
exception, which will be triggered when too many people enter the lift:
class Lift { class X::Lift::Overload is Exception { method message { 'Too many people!' } } has $.capacity = 5; has $!people; method enter(Int $n = 1) { $!people += $n; X::Lift::Overload.new.throw if $!people > $!capacity; } }
We don't need the exception class outside the Lift
class, so it is better to restrict...