【问题标题】:What is the exception that should be thrown when user input is blank?当用户输入为空时应该抛出什么异常?
【发布时间】:2020-08-21 16:34:44
【问题描述】:

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

例如,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
}

我搜索了throwerrorcatch,但找不到。

【问题讨论】:

    标签: error-handling try-catch tcl throw


    【解决方案1】:

    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 通过throw 调用的type 词进行交互。我们抛出“Value Empty”或“Value Invalid”。在陷阱中,我们完全匹配Value,但我们不会完全匹配*。事后看来,* 不应该在那里。 try 手册页初读时不是很清楚:

    陷阱 模式 变量列表 脚本

    如果 body 的评估导致错误并且解释器状态字典中 -errorcode 的前缀等于 pattern。从 -errorcode 中提取的前缀词数等于 pattern 的 list-length,并且在 -errorcode 和 pattern 进行比较。

    pattern 不是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
    }
    

    【讨论】:

    • 感谢您的帮助。 trap* 的使用是否记录在任何地方?
    • 有一点层次结构,POSIX 是用于来自操作系统的事物的前缀,TCL 是用于源自 Tcl 实现的错误。除此之外……世界对代码作者开放。我想如果你正在写一个包,首先使用你的包名可能是个好主意?
    • @donal,是否有完整的“核心”错误代码列表记录在任何地方?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-30
    • 1970-01-01
    • 1970-01-01
    • 2015-05-12
    • 1970-01-01
    • 1970-01-01
    • 2012-03-24
    相关资源
    最近更新 更多