gpt4 book ai didi

error-handling - 用户输入为空时应该抛出什么异常?

转载 作者:行者123 更新时间:2023-12-03 07:52:23 26 4
gpt4 key购买 nike

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

例如,Python具有 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 error catch ,但是找不到它。

最佳答案

Tcl没有预定义的异常层次结构。 throw命令带有2个参数: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"
}
throwtry通过 type调用的 throw字进行交互。我们抛出“空值”或“无效值”。在陷阱中,我们完全匹配 Value,但不会完全匹配 *。事后看来, *不应该存在。
初次阅读时, try 联机帮助页并不十分清晰:

trap pattern variableList script

This clause matches if the evaluation of body resulted in an error and the prefix of the -errorcode from the interpreter's status dictionary is equal to the pattern. The number of prefix words taken from the -errorcode is equal to the list-length of pattern, and inter-word spaces are normalized in both the -errorcode and pattern before comparison.



模式不是 regexpstring match意义上的模式:它是一个单词列表,该单词列表与try正文中抛出的单词列表一一对应。
try可以用多个陷阱实现以具有级联的“陷阱”:
try {
set answer [getJobinfo "What is the answer to this question"]

} trap {Value Empty} msg {
do something specific here

} trap {Value Invalid} msg {
do something specific here

} trap {Value} msg {
do something general for some other "throw {Value anything} msg"

} on error e {
this can be default catch-all for any other error

} finally {
any cleanup code goes here
}

关于error-handling - 用户输入为空时应该抛出什么异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61639858/

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