Version 10 of Exception Handling

Updated 2012-09-19 00:07:09 by SEH

Purpose: to discuss the issues of when and how to write exception handling code.

  • What is exception handling?
  • When should one write exception handling code?
  • When should one NOT write exception handling code?
  • What tools exist to aid in writing exception handling code?
  • How exception handling works

hv - Here is a short snippet showing how to use the return command with -code error to throw an exception

    proc double {x} {
        if {![string is integer $x]} {
            return -code error "double expects an int, not '$x'"
        }
    
        return [expr {$x * 2}]
    }
    
    set x 5
    puts "x = $x"
    puts "2x = [double $x]"
    
    set x "Hello"
    puts "x = $x"
    if {[catch {puts "2x = [double $x]"} errmsg]} {
        puts "Error: $errmsg"
    }

Output:

    x = 5
    2x = 10
    x = Hello
    Error: double expects an int, not 'Hello'

See: try ... finally ...