是否有可能捕获glob的错误输出?

问题描述 投票:0回答:2

假设我的glob中包含以下try/trap/finally命令:

proc generateSubmissionFolder {cover_letter_resume submission_path} {
   set submission_parent [file dirname $submission_path]
   set latest_submission_folder [lindex [lsort [glob -directory $submission_parent -type d *]] end]
   set latest_submission_file [lindex [glob -directory $latest_submission_folder *[file extension $cover_letter_resume]] end]
   createSubmissionFolder $latest_submission_file $submission_path
}


proc createSubmissionFolder {source destination} {
    puts "Creating $destination folder."
    file mkdir $destination
    puts "Copying $source to $destination"
    file copy $source $destination
}


try {

    # I gathered user input and stored them in the variables $company_name and $position.

    set submission_path [file join $company_name $position $yearmonthday]

    if {[file exists [file dirname $submission_path]]} {
        generateSubmissionFolder $coverletterresume $submission_path
    } else {
        createSubmissionFolder $coverletterresume $submission_path
    } 

} trap {Value Empty} {errormessage} {
   puts "$errormessage"
} finally {
   puts "$argv0 exiting."
}

如果未找到文件夹,我想提供一条人类可读的错误消息,但是我不确定要捕获什么错误。根据我先前的问题answer

Tcl没有预定义的异常层次。

我尝试的唯一解决方法是使用-nocomplain开关,然后检查latest_submission_folder是否为空白。

是否有捕获FileNotFoundFolderNotFound错误的方法?

tcl throw
2个回答
1
投票

对于像您这样的例子这样的琐碎情况,请使用on error处理程序,而不要使用trap。或使用catch代替catch

try会话示例:

tclsh

或者如果您确实想使用% try { glob *.bar } on error {what} { puts "Ooops: $what" } Ooops: no files matched glob pattern "*.bar" % if {[catch { glob *.bar } result] == 1} { puts "Ooops: $result" } Ooops: no files matched glob pattern "*.bar" ,因为您还想处理来自更复杂代码的许多其他可能的特定错误,则trap会在失败时引发glob

TCL OPERATION GLOB NOMATCH

您可以通过类似以下命令发现对于任何给定命令的特定错误,% try { glob *.bar } trap {TCL OPERATION GLOB NOMATCH} {msg} { puts "Ooops: $msg" } Ooops: no files matched glob pattern "*.bar" 中使用什么:

trap

0
投票

在这种特定情况下,] >> % catch { glob *.bar } result errdict 1 % dict get $errdict -errorcode TCL OPERATION GLOB NOMATCH 有一个帮助的选项:glob。它关闭了没有匹配的错误,因为只有许多用例可以很好地处理空的返回列表,该错误才真正用于交互用途。 (这是出于历史原因的方式,并且以这种方式进行维护,因此我们不会破坏使用它的大量现有脚本。随着语言的发展,这并不太可怕。)

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