How to catch an exception in Perl 6

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.

Note! This site is about Perl 6.
If you are looking for a solution for the current production version of Perl 5, please check out the Perl 5 tutorial.

use v6;

my $x = 10;
my $y = 0;

my $z = $x / $y;

my $exception;
	say $z;
		default {
			$exception = $_;

if ($exception) {
	say "There was an exception: $exception";

say "still running";


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.

The Perl 6 Tricks and Treats newsletter has been around for a while. If you are interested to get special notification when there is new content on this site, it is the best way to keep track:
Full name:
This is a newsletter temporarily running on my personal site ( using Mailman, till I implement an alternative system in Perl 6.
Gabor Szabo
Written by Gabor Szabo

Published on 2013-12-08


In the comments, please wrap your code snippets within <pre> </pre> tags and use spaces for indentation.
comments powered by Disqus
Suggest a change
Elapsed time: 3.3926891

Perl 6 Tricks and Treats newsletter

Register to the free newsletter now, and get updates and news.