본문으로 바로가기

Tcl의 try & trap & finally

category 카테고리 없음 2024. 4. 22. 15:50

Tcl8.6부터 catch와는 다른 새로운 에러 처리 구문인 try, trap, finally 추가되었습니다.  
C++의 try .. catch.. finally와 같은 의미로, 간단한 설명과 함께 아래의 예들로 대신합니다.

try내 body를 실행시 trap으로 지정되어 있는 에러가 발생하면 해당 trap내의 body를 수행하며, trap으로 지정되지 않은 (불특정) 예외 에러 발생 시 on error의 body를 수행합니다. 마지막으로 finally 구문을 수행하여, 에러 처리를 종료합니다.

set f [open /some/file/name a]
try {
    puts $f "some message"
    # ...
} finally {
    close $f
}
try {
	set f [open /some/file/name r]
} trap {POSIX ENOENT} msg {
	puts "in trap: $msg"
} on error {msg} {
	puts "in on error: $msg"
} finally {
	return
}
try {
    set f [open /some/file/name]
} trap {POSIX EISDIR} {} {
    puts "failed to open /some/file/name: it's a directory"
} trap {POSIX ENOENT} {} {
    puts "failed to open /some/file/name: it doesn't exist"
}
proc read_hex_file {fname} {
        set f [open $fname "r"]
        set data {}
        try  {
                while { [gets $f line] >= 0 } {
                        append data [binary format H* $line]
                }
        } trap {POSIX} {} {
                puts "POSIX-type error"
        } on error {em} {
                error "Could not process file '$fname': $em"
        } finally {
                close $f
        }
}