假設我有一個模塊Bar,它是模塊Foo的子類包裝器。我想調用Bar的方法來模擬Foo的 - 甚至是致命的錯誤。到目前爲止,很容易;我只是打電話給SUPER方法。如何捕獲並重新拋出Perl中的錯誤?
sub stuff {
# Do stuff here
SUPER::stuff(@_);
# Do more stuff here
}
但是,讓我們假設我想抓住,記錄並重新拋出任何致命錯誤SUPER::stuff()
產生。前兩步很容易:
sub stuff {
# Do stuff here
eval {
SUPER::stuff(@_);
};
[email protected] and log("Naughty, naughty: [email protected]");
# Do more stuff here
}
...但我不知道如何做最後一部分。如何重新拋出錯誤,使得主叫方無法區分Foo->stuff()
的呼叫和Bar->stuff()
的呼叫?我可以在日誌聲明後插入die [email protected]
,並期望它能做我想做的事情嗎?或者在這裏有細微差別可能會讓我陷入困境?
避免使用檢查'$ @'eval'後',尤其是面向對象的代碼。參見['Try :: Tiny'](http://search.cpan.org/~doy/Try-Tiny-0.09/lib/Try/Tiny.pm#BACKGROUND) – mob 2011-05-10 20:16:38
@mob:那很荒謬。 – tchrist 2011-05-11 23:10:12
@tchrist,我同意,但我也看到'$ @'在生產代碼中出現'eval' bug後重置。 – 2011-05-12 14:50:02