我已经搜索了一段时间,但我肯定已经错过了,是否有任何文档说明当值不正确/空白时应该抛出什么?
例如,Python
具有ValueError
,文档中清楚地说明了何时使用它。
我有以下方法:
ValueError
我已经搜索了proc getJobinfo {question} {
puts -nonewline "$question: "
flush stdout
gets stdin answer
set cleanedanswer [string trim [string totitle $answer]]
if {$cleanedanswer eq ""} {
# What error should be thrown?
}
return $cleanedanswer
}
,throw
和throw
,但找不到它。
Tcl没有预定义的异常层次。 throw命令带有2个参数:error
是单词列表; error
是人类的错误消息。
您可以做类似的事情
catch
如果您想捕获该错误:
catch
type
和message
通过proc getJobinfo {question} {
...
if {$cleanedanswer eq ""} {
throw {Value Empty} "Please provide a suitable answer."
} elseif {[string length $cleanedanswer] < 5} {
throw {Value Invalid} "Your answer is too short."
} else ...
return $cleanedanswer
}
调用的try {
set answer [getJobinfo "What is the answer to this question"]
} trap {Value *} msg {
puts "Value Error: $msg"
}
字进行交互。我们抛出“空值”或“无效值”。在陷阱中,我们完全匹配throw
,但不完全匹配try
。事后看来,type
不应该存在。初次阅读时,throw
联机帮助页不是非常清晰:
trap pattern variableList script
如果[的评估导致错误并且解释器的状态词典中-errorcode的前缀等于pattern,则此子句匹配。从-错误代码中提取的前缀词的数量等于模式的列表长度,并且在-错误代码和模式中对词间空格进行了归一化比较之前。
pattern
在Value
或*
的意义上不是一个模式:它是一个单词列表,与尝试body中抛出的单词列表一一对应。 *
可以用多个陷阱实现,以具有级联的“陷阱”: