In Perl 6 every block acts as a try exception if there is a CATCH block in it. Inside the CATCH block one can use a default block to catch all the exceptions.
use v6; my $x = 10; my $y = 0; my $z = $x / $y; my $exception; { say $z; CATCH { default { $exception = $_; } } } if ($exception) { say "There was an exception: $exception"; } say "still running";
Output:
There was an exception: Divide by zero still running
One very important thing to note here. The actual exception was caused bye the division: my $z = $x / $y;.
That did not throw an exception yet. The exception was thrown only when we tried to use the variable that had an invalid value.
The actual exception object is in $_, but we copied it to a variable just so we can have it outside the block. In most cases this is not really necessary.
What is important though, is that it is not just a simple string as the above output would suggest.
It is actually an instance of the X::Numeric::DivideByZero class. It has methods such as backtrace that returns a list of Backtrace::Frame instances. Each Backtrace::Frame instance has several attributes including file and line that can help identify where the exception was created and where was it thrown.
Published on 2013-12-08