Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 36 ยท Procedures and Control Flow

Exceptions, try/except and defer

Handle errors in Nim with try/except/finally, raise your own exceptions, tell Defects from CatchableErrors, clean up with defer, and use assert, with C stand-ins.

Things go wrong: a file is missing, user input is not a number, an index is out of range. Nim offers exceptions for errors that a caller might want to handle, defects for programmer bugs, and the defer statement for cleanup that must happen no matter how a block ends. This lesson shows how to use all three and how they differ.

Nim snippets are read-only here (no Nim compiler on this site); C stand-ins can be run on the page.

Catching exceptions

NIM
import std/strutils

try:
  let n = parseInt("12x")
  echo "parsed ", n
except ValueError:
  echo "that is not a number"

The try block runs normally until something raises an exception. Control then jumps to the first matching except clause. After the clause finishes, the program continues after the whole try statement.

You can capture the exception object and inspect it:

NIM
try:
  discard parseInt("abc")
except ValueError as e:
  echo "error: ", e.msg

Several clauses and a catch-all are allowed. Put specific types first:

NIM
try:
  riskyWork()
except IOError:
  echo "I/O problem"
except ValueError, OverflowDefect:
  echo "bad value"
except CatchableError as e:
  echo "other error: ", e.msg

else and finally

NIM
try:
  echo "work"
except IOError:
  echo "failed"
finally:
  echo "always runs"

The finally block runs whether or not an exception happened, even when the try returns or breaks. It is the classic place to release resources such as files.

try as an expression

Like if, a try can produce a value. Each branch must give the same type:

NIM
let number = try: parseInt("42") except ValueError: -1

Raising exceptions

NIM
type
  InsufficientFunds = object of CatchableError

proc withdraw(balance, amount: int): int =
  if amount > balance:
    raise newException(InsufficientFunds, "need " & $(amount - balance) & " more")
  balance - amount

try:
  discard withdraw(50, 80)
except InsufficientFunds as e:
  echo e.msg             # need 30 more

raise newException(Type, "message") creates and throws an exception. Define your own by inheriting from CatchableError. Exception types form a hierarchy, and an except clause for a parent type also catches its children.

Defects versus errors

Kind Base type Meaning Examples
Recoverable error CatchableError Something outside the program's control failed IOError, OSError, ValueError, KeyError
Defect Defect A bug in the program IndexDefect, OverflowDefect, DivByZeroDefect, AssertionDefect, NilAccessDefect

You can catch a defect, but you should normally not: it means your code is wrong, and the fix is to correct the code, not to hide it. In release builds some of these checks are removed entirely.

flowchart TD
  E["Exception"] --> D["Defect<br/>(bugs)"]
  E --> C["CatchableError<br/>(recoverable)"]
  D --> I["IndexDefect, OverflowDefect, ..."]
  C --> V["ValueError, IOError, KeyError, ..."]

Caption: the two branches of Nim's exception tree.

defer: cleanup at scope exit

defer registers a block to run when the enclosing scope ends, however it ends (normal flow, return, break, or an exception). Declare the cleanup right next to the acquisition:

NIM
proc readFirstLine(path: string): string =
  let f = open(path)
  defer: f.close()          # runs when readFirstLine returns or fails
  result = f.readLine()

Several defer blocks run in reverse order, last registered first, like stacking plates. Compared with finally, defer does not add nesting, so code stays flat.

Assertions and contracts

NIM
func safeDiv(a, b: int): int =
  assert b != 0, "divisor must not be zero"
  a div b

assert is checked in debug builds and removed by -d:danger; doAssert is always checked. A failed assertion raises AssertionDefect. Use them for conditions that should never be false.

To state which exceptions a procedure may raise, use {.raises: [ValueError].}; the compiler then verifies the claim, and {.raises: [].} promises no exceptions at all.

Stand-in: try and finally with setjmp

C has no exceptions, but setjmp/longjmp can emulate them: setjmp marks the try, and longjmp is the raise. This stand-in demonstrates a catch and a cleanup that always runs. It is not how Nim implements exceptions (Nim uses either C++-style exceptions or setjmp depending on settings); it only shows the control flow.

C Stand-in: raise, catch and finally

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Stand-in: defer as automatic cleanup

GCC and Clang support a cleanup attribute that runs a function when a variable leaves scope. It is a decent model for Nim's defer.

C Stand-in: defer-like cleanup in reverse order

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Notice the order: the file opened last is closed first, which is what Nim's defer guarantees.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. When does a finally block run?

    finally is for cleanup that must always happen.
  2. 2. Which should you normally NOT catch?

    Defects signal bugs; fix the code instead of hiding them.
  3. 3. What does defer do?

    defer is scope-exit cleanup; several defers run in reverse order.
  4. 4. How do you define your own recoverable exception type?

    Inherit from CatchableError (or a more specific child) and raise it with newException.

Summary

  • try/except/finally handle exceptions; except T as e gives you the exception object.
  • raise newException(Type, msg) throws; define custom types from CatchableError.
  • Defects are bugs; CatchableError is for recoverable failures.
  • defer runs cleanup at scope exit, in reverse order; assert and doAssert check assumptions.

Next: Arrays and sequences