Perl尝试捕获用户定义的异常
发布时间:2020-12-16 06:21:33 所属栏目:大数据 来源:网络整理
导读:我想知道perl是否有一些类似于 python的try catch机制,我可以提高用户定义的异常并相应地处理. Python代码: try: number = 6 i_num = 3 if i_num number: raise ValueTooSmallError elif i_num number: raise ValueTooLargeError break except ValueTooSmal
|
我想知道perl是否有一些类似于
python的try catch机制,我可以提高用户定义的异常并相应地处理.
Python代码: try:
number = 6
i_num = 3
if i_num < number:
raise ValueTooSmallError
elif i_num > number:
raise ValueTooLargeError
break
except ValueTooSmallError:
print("This value is too small,try again!")
print()
except ValueTooLargeError:
print("This value is too large,try again!")
print()
我知道perl尝试抓住机制,如下所示: sub method_one {
try {
if ("number" eq "one") {
die("one");
} else {
die("two");
}
} catch {
if ($@ eq "one") {
print "Failed at one";
}
}
}
要么 eval {
open(FILE,$file) ||
die MyFileException->new("Unable to open file - $file");
};
if ($@) {
# now $@ contains the exception object of type MyFileException
print $@->getErrorMessage();
# where getErrorMessage() is a method in MyFileException class
}
我更专注于对捕获的if检查.有没有办法可以避免检查我遇到的不同类型的错误. 解决方法
最接近的解决方案可能是直接的
failures对象,TryCatch用于类型检查.
use failures qw(
Example::Value_too_small
Example::Value_too_large
);
use TryCatch;
try {
my $number = 6;
my $i_num = 3;
if ($i_num < $number) {
failure::Example::Value_too_small->throw({
msg => '%d is too small,try again!',payload => $i_num,});
} elsif ($i_num > $number) {
failure::Example::Value_too_large->throw({
msg => '%d is too large,});
}
} catch (failure::Example::Value_too_small $e) {
say sprintf $e->msg,$e->payload;
} catch (failure::Example::Value_too_large $e) {
say sprintf $e->msg,$e->payload;
} finally {
...
}
您可以从这里升级到custom::failures,Throwable,Exception::Class. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
