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

What is the exception that should be thrown when user input is blank?

我已经搜索了一段时间,我确定我已经错过了,是否有任何文档说明当值为 incorrect/blank 时应该抛出什么?

例如,PythonValueError 并且文档明确说明了何时使用它。

我有以下方法:

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, and catch,但没找到。

Tcl 没有预定义的异常层次结构。 throw 命令有两个参数: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 通过 throw 调用的 type 词进行交互。我们抛出 "Value Empty" 或 "Value Invalid"。在陷阱中,我们精确匹配 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.

pattern 不是 regexpstring match 意义上的模式:它是与try body.

中抛出的单词列表

try可以用多个陷阱实现级联"catches":

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
}