Recent Changes - Search:

Oktatás

* Programozás 1
  + feladatsor
  + GitHub oldal

* Szkriptnyelvek
  + feladatsor
  + quick link

Teaching

Programming 1 (BI)
  ▸ exercises
  ▸ quick link

teaching assets


Félévek

* 2025/26/2
* archívum


Linkek

* kalendárium
* tételsorok
* jegyzetek
* szakdolgozat / PhD
* ösztöndíjak
* certificates
* C lang.
* C#
* D lang.
* Java
* Nim
* Nim2
  + exercises
* XC=BASIC
* old
  ✦C++, ✦Clojure, ✦Scala


[ edit | logout ]
[ sandbox | passwd ]

execute a proc before quitting

See std/exitprocs

Example

import 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 exception

What 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 / quit

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)
  #
  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 main() call inside a try block.

quit() triggers the exit procs.

Alternatively, we could also put just readFile() inside a try block:

# ...
try:
  echo readFile("doesnt_exists.txt")
except IOError as e:
  stderr.writeLine "File error: ", e.msg
  quit(1)
# ...
Cloud City

  

Blogjaim, hobbi projektjeim

* The Ubuntu Incident
* Python Adventures
* @GitHub
* heroku
* extra
* haladó Python
* YouTube listák


Debrecen | la France


[ edit ]

Edit - History - Print *** Report - Recent Changes - Search
Page last modified on 2026 June 01, 20:51