1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
|
#!/usr/bin/perl
use v5.14;
use warnings;
use Test2::V0;
use Syntax::Keyword::Try;
# try success
{
my $s;
try {
$s = 1;
}
catch ($e) {
$s = 2;
}
is( $s, 1, 'sucessful try{} runs' );
}
# try catches
{
my $s;
ok( eval {
try {
die "oopsie";
}
catch ($e) { }
$s = 3;
"ok";
}, 'try { die } is not fatal' );
is( $s, 3, 'code after try{} runs' );
}
# exceptions that are false
{
my $caught;
try {
die FALSE->new;
}
catch ($e) {
$caught++;
}
ok( $caught, 'catch{} sees a false exception' );
{
package FALSE;
use overload 'bool' => sub { 0 };
sub new { bless [], shift }
}
}
# catch sees exception
{
my $caught;
try {
die "oopsie";
}
catch ($e) {
$caught = $e;
}
like( $caught, qr/^oopsie at /, 'catch{} sees $@' );
}
# catch block executes
{
my $s;
try {
die "oopsie";
}
catch ($e) {
$s = 4;
}
is( $s, 4, 'catch{} of failed try{} runs' );
}
# catch can rethrow
{
my $caught;
ok( !eval {
try { die "oopsie"; }
catch ($e) { $caught = $e; die $e }
}, 'die in catch{} is fatal' );
my $e = $@;
like( $e, qr/^oopsie at /, 'exception is thrown' );
like( $caught, qr/^oopsie at /, 'exception was seen by catch{}' );
}
# catch without VAR
{
try {
die "caught\n";
}
catch {
my $e = $@;
is( $e, "caught\n", 'exception visible in $@' );
}
}
# catch lexical does not retain
{
my $destroyed;
sub Canary::DESTROY { $destroyed++ }
try {
die bless [], "Canary";
}
catch ($e) {
# don't touch $e
}
ok( $destroyed, 'catch ($var) does not retain value' );
}
{
no Syntax::Keyword::Try;
sub try { return "normal function" }
is( try, "normal function", 'try() parses as a normal function call' );
}
done_testing;
|