当用户输入为空白时应该引发什么异常?

问题描述 投票:1回答:1

我已经搜索了一段时间,但我肯定已经错过了,是否有任何文档说明当值不正确/空白时应该抛出什么?

例如,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 } throwthrow,但找不到它。

error-handling try-catch tcl throw
1个回答
1
投票

Tcl没有预定义的异常层次。 throw命令带有2个参数:error是单词列表; error是人类的错误消息。

您可以做类似的事情

catch

如果您想捕获该错误:

catch

typemessage通过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中抛出的单词列表一一对应。 *可以用多个陷阱实现,以具有级联的“陷阱”:

try

© www.soinside.com 2019 - 2024. All rights reserved.