|
Oktatás * Programozás 1 * Szkriptnyelvek Teaching • Programming 1 (BI) Félévek Linkek * kalendárium |
Nim2 /
execute a proc before quittingSee std/exitprocs Exampleimport std/exitprocs proc one() = echo "one" proc two() = echo "two" proc main() = echo "hello" when isMainModule: addExitProc(one) addExitProc(two) # main() The registered procs go into a stack (LIFO), i.e. the procs will be called in a reverse order. Output: hello two one Unhandled exceptionWhat happens if we have an unhandled exception and the program terminates with an ugly error message? import std/exitprocs proc one() = echo "one" proc two() = echo "two" proc main() = echo "hello" echo readFile("doesnt_exists.txt") when isMainModule: addExitProc(one) addExitProc(two) # main() Output: hello Error: unhandled exception: cannot open: doesnt_exists.txt [IOError] The registered procs are not executed :( Unhandled exceptions bypass exit procs. Handled exception / quitimport std/exitprocs proc one() = echo "one" proc two() = echo "two" proc main() = echo "hello" echo readFile("doesnt_exists.txt") when isMainModule: addExitProc(one) addExitProc(two) # try: main() except Exception as e: stderr.writeLine "Error: ", e.msg quit(1) Output: hello Error: cannot open: doesnt_exists.txt two one To overcome the previous problem, we need to catch the exception. A simple way is to put the whole
Alternatively, we could also put just # ... try: echo readFile("doesnt_exists.txt") except IOError as e: stderr.writeLine "File error: ", e.msg quit(1) # ... |
![]() Blogjaim, hobbi projektjeim * The Ubuntu Incident [ edit ] |