Perl で try 〜 catch 節を使ってみる

#!/usr/bin/env perl
use strict;
use warnings;
use Encode;
use Error qw(:try);

my $div = shift || 0;

# try {...} catch Error with {...} finally {...} の
# {} はスコープを作るためのものです。
# See http://blog.livedoor.jp/dankogai/archives/50982802.html

try {
    # try節
    my $result = 1 / $div;
    print "Answer is " . $result . "\n";
}

catch Error with {
    # catch節
    my $error = shift;
    print "Error occured: " . $error . "\n";
}

finally {
    # finally節
    print "1 is divided by " . $div . "\n";
}; # 最後の ; を忘れないように

エラーを発生させない場合の動作結果

% ./divide.pl 1
Answer is 1
1 is divided by 1

% ./divide.pl 2
Answer is 0.5
1 is divided by 2

% ./divide.pl 3
Answer is 0.333333333333333
1 is divided by 3

% ./divide.pl 0.1
Answer is 10
1 is divided by 0.1

エラーを発生させた場合の動作

% ./divide.pl
Error occured: Illegal division by zero at ./divide.pl line 15.
1 is divided by 0

% ./divide.pl 0
Error occured: Illegal division by zero at ./divide.pl line 15.
1 is divided by 0

% ./divide.pl a
Argument "a" isn't numeric in division (/) at ./divide.pl line 15.
Error occured: Illegal division by zero at ./divide.pl line 15.
1 is divided by a