例外処理。
き、気持ち悪い…orz
昨晩から、また頭痛始まっちゃって
横になると、ますます痛いからアスピリン頼み。
やっとなんとか眠れても、朝もまだ頭ボカーンって感じで
ほんと、これでドラム教室行けるのかしら?(汗)
だのに何もしないでいるのが辛い人間なので(苦笑)
perlの例外処理について、メモ。
で、早い話「Object Oriented Exception Handling in Perl」を読んで書き写しただけ。
本当は Exception::Class 使えばいいんだけど、
標準モジュールじゃないから、ちょっと問題があったりなんかして。
・Exception.pm
package Exception;use base qw(Error);
use overload ('""' => 'stacktrace');
sub new {
my $self = shift;
my $text = shift || '';
my @args = ();
local $Error::Depth = $Error::Depth + 1;
local $Error::Debug = 1;
$self->SUPER::new(-text => $text, @args);
}
1;
package Exception::FirstException;
use base qw(Exception);
1;
package Exception::SecondException;
use base qw(Exception);
1;
・TestClass.pm
package TestClass;use strict;
use warnings;
use Error qw(:try);
use Exception;
sub new {
my $me = shift;
my $param = {
};
bless $param, $me;
}
sub testThrow {
my $me = shift;
use ChildClass;
my $objClass = ChildClass->new();
return $objClass->testThrow();
}
1;
・TestClass.pm
package TestChildClass;use base TestClass;
sub testThrow {
my $me = shift;
throw Exception::FirstException('ここで例外投げてまっせー');
}
1;
・test.pl
#!/usr/bin/perl -wuse strict;
use warnings;
use Exception;
use Error qw(:try);
try {
use TestClass;
my $objClass = TestClass->new();
$objClass->testThrow();
}
catch Exception::FirstException with {
# FirstException 用の何か処理やら表示やら
my $exception= shift;
warn $exception;
}
catch Exception::SecondException with {
# SecondException 用の何か処理やら表示やら
my $exception= shift;
warn $exception;
}
catch Error with {
# 普通の例外用の何か処理やら表示やら
my $exception = shift;
warn $exception;
}
finally {
# 必要ならロールバック処理とか
};
exit;
で、これを実行すると
$ ./test.plここで例外投げてまっせー at /home/anigon/exception/TestChildClass.pm line 13
TestChildClass::isCorrectString('TestChildClass=HASH(0x101bc588)') called at /home/anigon/exception/TestClass.pm line 22
TestClass::isCorrectString('TestClass=HASH(0x101bc504)') called at ./test.pl line 15
例えば /var/log/apache/error_log なんかに、こんな感じ↑に出力される、と。
ちゃんと、どこから呼ばれて、どこで例外発生したかわかって便利だね。
てな訳で、存在するはずのファイルがない、とか
外部コマンド叩いたら、無反応とか
致命的なエラーの時に、例外処理入れられたらいいなぁ。