10. 例外処理
10.1. 例外を捕捉する
例外 とは、実行時に問題が発生した際に起こる特別な動作のことです。
例外を 投げる と表現します。
下のスクリプトは問題なく実行されます:
my Str $name;
$name = "Joanna";
say "Hello " ~ $name;
say "How are you doing today?"
出力
Hello Joanna How are you doing today?
下のスクリプトは例外を投げます:
my Str $name;
$name = 123;
say "Hello " ~ $name;
say "How are you doing today?"
出力
Type check failed in assignment to $name; expected Str but got Int in block <unit> at exceptions.pl6:2
エラーが発生した場合(今回のケースでは文字列変数に数を代入している)、プログラムの実行は止まります。残りのコードは、たとえ正しくても評価されません。
例外処理 とは、スクリプトの実行が続くように、投げられた 例外を 捕捉する ことです。
my Str $name;
try {
$name = 123;
say "Hello " ~ $name;
CATCH {
default {
say "Can you tell us your name again, we couldn't find it in the register.";
}
}
}
say "How are you doing today?";
出力
Can you tell us your name again, we couldn't find it in the register. How are you doing today?
例外処理には try-catch
ブロックを使います。
try {
#code goes in here
#if anything goes wrong, the script will enter the below CATCH block
#if nothing goes wrong the CATCH block will be ignored
CATCH {
default {
#the code in here will be evaluated only if an exception has been thrown
}
}
}
CATCH
ブロックの定義の方法は、 given
ブロックと同じです。
つまり、さまざまな違うタイプの例外を 捕捉 して、さまざまに処理できるということです。
try {
#code goes in here
#if anything goes wrong, the script will enter the below CATCH block
#if nothing goes wrong the CATCH block will be ignored
CATCH {
when X::AdHoc { #do something if an exception of type X::AdHoc is thrown }
when X::IO { #do something if an exception of type X::IO is thrown }
when X::OS { #do something if an exception of type X::OS is thrown }
default { #do something if an exception is thrown and doesn't belong to the above types }
}
}
10.2. 例外を投げる
Perl6では、例外の捕捉ができるだけでなく、明示的に例外を投げることもできます。
2種類の例外を投げることができます:
-
アドホックな(ad-hoc)例外
-
型付き例外
アドホック
my Int $age = 21;
die "Error !";
型付き
my Int $age = 21;
X::AdHoc.new(payload => 'Error !').throw;
アドホックな例外は die
サブルーチンの後に例外メッセージを付けて投げます。
型付き例外はオブジェクトです。それで、上の例では .new()
コンストラクタが使われています。
すべての型付き例外は X
から継承しています。以下にいくつか例を挙げます:
X::AdHoc
は、最もシンプルな例外型です。
X::IO
は、IOエラーに関するものです。
X::OS
は、OSエラーに関するものです。
X::Str::Numeric
は、文字列から数への強制変換に関するものです。
すべての例外型と関係するメソッドに関しては、 http://doc.perl6.org/type.html(英語) で X で始まる型を調べてください。 |