Quick Trick: Catching a Perl 6 warning

While testing a module I wanted to check that a deprecation warning shows up. Warnings are a special sort of exception that you can catch in a CONTROL block.

Warning!

In my test file I add a CONTROL phaser. This catches the action of block exiting things including return, fail, redo, next, last, take, and in this case, warn:

{ # with forced find to Not work recursive
CONTROL {
	my $label = ':recursive warns about deprecation';
	when CX::Warn { like $_.message, /deprecated/, $label; }
	default       { fail( $label ); }
	}
my $res = find(:dir<t/dir1>, :name<file.bar>, recursive => False);
is $res.elems, 1, 'name with a string';
}

You won’t catch these in a normal CATCH block:

sub foow { warn "This is a warning" }
sub food { die  "This is a death" }

{
CONTROL {
	when CX::Warn { put "Caught warning in CONTROL" }
	}
foow();
}


try {
CATCH {
	when CX::Warn  { put "Caught warning in CATCH" }
	when  X::AdHoc { put "Caught death in CATCH" }
	default { put "Caught {$_.^name} with {$_.message}" }
	}
foow();
food();
}

The output shows that the CONTROL caught the warning from the first call but the CATCH let it pass through in the second:

Caught warning in CONTROL
Caught death in CATCH
This is a warning
  in sub foow at /Users/brian/Desktop/test.p6 line 5

Leave a Reply

Your email address will not be published. Required fields are marked *