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 ]

The `raises` pragma

The raises pragma can be used to explicitly define which exceptions a proc/iterator/method/converter is allowed to raise. The compiler verifies this:

import std/rdstdin     # for inputExtra()

proc inputExtra(prompt: string = ""): string {.raises: [EOFError].} =
  var line: string = ""
  let val = readLineFromStdin(prompt, line)    # line is modified
  if not val:
    raise newException(EOFError, "abort")
  line

It means: "this proc may raise the exception EOFError". This is true, so it compiles. ✔️

This one also works ✅

The following code also compiles:

import std/rdstdin     # for inputExtra()

proc inputExtra(prompt: string = ""): string {.raises: [EOFError, ValueError].} =
  var line: string = ""
  let val = readLineFromStdin(prompt, line)    # line is modified
  if not val:
    raise newException(EOFError, "abort")
  line

The {.raises: [EOFError, ValueError].} pragma is a promise you make to the compiler, not a requirement that the proc must raise those exceptions. It means:

"This proc will raise at most these exception types (and their subtypes)."

It's an upper bound / whitelist. The compiler verifies that no exception outside the list can escape the proc — it does not verify that every listed exception is actually reachable.

This one fails to compile ❌

import std/rdstdin     # for inputExtra()

# advanced solution
proc inputExtra(prompt: string = ""): string {.raises: [ValueError].} =
  var line: string = ""
  let val = readLineFromStdin(prompt, line)    # line is modified
  if not val:
    raise newException(EOFError, "abort")
  line

Here, with {.raises: [ValueError].} we say that "the proc may raise the exception ValueError". The compiler checks it and finds that this is not the case. The proc can raise an EOFError exception but it's not in the whitelist ⇒ it won't compile.

The {.raises: [].} idiom

When the raises list is empty, then we get a guarantee that the proc cannot raise any exception.

If the proc raises an exception, we'll get a compile error.

proc safeFoo() {.raises: [].} =
  discard  # fine

proc safeFoo2() {.raises: [].} =
  raise newException(ValueError, "!")  # compile error
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 April 25, 15:21