gpt4 book ai didi

Perl try catch 用户定义的异常

转载 作者:行者123 更新时间:2023-12-03 16:01:30 25 4
gpt4 key购买 nike

我想知道 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 有像下面这样的 try catch 机制:
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
}

我更专注于 如果 检查渔获量。有没有办法可以避免检查我发现的不同类型的错误。

最佳答案

最接近的解决方案可能是直截了当的 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, try again!',
payload => $i_num,
});
}
} 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 .

关于Perl try catch 用户定义的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48983344/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com