gpt4 book ai didi

exception - 为什么 Perl 6 会为我的子集类型抛出 X::AdHoc 异常?

转载 作者:行者123 更新时间:2023-12-04 08:04:21 25 4
gpt4 key购买 nike

这是 Perl 6 中报告的错误:X::AdHoc instead of X::TypeCheck::Binding with subset parameter ,于 2015 年 11 月首次报道。

在玩我的 Perl 6 模块时 Chemisty::Elements , 我遇到了 Exception我没想到的问题。

我定义了一个类型,ZInt ,它将数字限制为在周期表上找到的序数(我在这里伪造了一点)。然后我使用该类型将参数约束到子例程。我希望得到某种 X::TypeCheck ,但我得到 X::AdHoc反而:

use v6;

subset ZInt of Cool is export where {
state ( $min, $max ) = <1 120>;
( $_.truncate == $_ and $min <= $_ <= $max )
or warn "Z must be between a positive whole number from $min to $max. Got <$_>."
};

sub foo ( ZInt $Z ) { say $Z }

try {
CATCH {
default { .^name.say }
}

foo( 156 );
}

首先,我收到两次警告,这很奇怪:

Z must be between a positive whole number from 1 to 120. Got <156>. in block at zint.p6 line 5 Z must be between a positive whole number from 1 to 120. Got <156>. in block at zint.p6 line 5 X::AdHoc



但是,我得到 X::AdHoc当我宁愿人们知道这是一个类型错误时输入。

我检查了没有 warn 会发生什么并得到 X::AdHoc再次:
subset ZInt of Cool is export where {
state ( $min, $max ) = <1 120>;
( $_.truncate == $_ and $min <= $_ <= $max )
};

所以,我想我可以抛出自己的异常:
subset ZInt of Cool is export where {
state ( $min, $max ) = <1 120>;
( $_.truncate == $_ and $min <= $_ <= $max )
or X::TypeCheck.new.throw;
};

但是,我收到一个警告:

Use of uninitialized value of type Any in string context Any of .^name, .perl, .gist, or .say can stringify undefined things, if needed.



在这一点上,我不知道在提示什么。我认为其中一种方法需要我没有提供的东西,但我没有看到任何关于 new 的参数的信息或 throw在文档中。

如何在没有警告的情况下获得我想要的类型以及我的自定义文本?

最佳答案

不要抛出异常或警告。相反,你想失败:

subset ZInt of Cool is export where {
state ( $min, $max ) = <1 120>;
( $_.truncate == $_ and $min <= $_ <= $max )
or fail "Z must be between a positive whole number from $min to $max. Got <$_>."
};

我相信这是你的意图。因您自己的异常而失败也很好,但是 X::TypeCheck 有一个错误。它应该要求“操作”或提供合理的默认值,就像它为“得到”和“预期”所做的那样。
subset ZInt of Cool is export where {
state ( $min, $max ) = <1 120>;
( $_.truncate == $_ and $min <= $_ <= $max )
or fail X::TypeCheck.new(
operation => "type check",
expected => ::('ZInt'),
got => $_,
);
};

关于exception - 为什么 Perl 6 会为我的子集类型抛出 X::AdHoc 异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40097868/

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