|
Oktatás * Programozás 1 * Szkriptnyelvek Teaching * Programming 1 (BI) Félévek Linkek * kalendárium |
Nim2 /
The `raises` pragmaThe 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 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 "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 The {.raises: [].} idiomWhen 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 |
![]() Blogjaim, hobbi projektjeim * The Ubuntu Incident [ edit ] |