在玩我的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类型.
我检查了没有警告会发生什么,并再次得到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的参数或扔进文档.
如何在没有警告的情况下获得我想要的类型以及我的自定义文本?
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中有一个bug.它应该要么“操作”要么提供合理的默认,就像它“得到”和“预期”一样.
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 => $_,); };