Recover in Nim

import std/strutils

proc mayPanic() =
  raise newException(Exception, "a problem")

proc main() =
  try:
    mayPanic()
    echo "After mayPanic()"
  except:
    let e = getCurrentException()
    echo "Recovered. Error:\n", e.msg

main()

Nim makes it possible to recover from an exception using a try-except block. This can stop an exception from aborting the program and let it continue with execution instead.

An example of where this can be useful: a server wouldn’t want to crash if one of the client connections exhibits a critical error. Instead, the server would want to close that connection and continue serving other clients.

Let’s break down the code:

  1. We import the strutils module, which provides string handling utilities.

  2. We define a mayPanic procedure that raises an exception:

    proc mayPanic() =
      raise newException(Exception, "a problem")
  3. In the main procedure, we use a try-except block to handle the exception:

    proc main() =
      try:
        mayPanic()
        echo "After mayPanic()"
      except:
        let e = getCurrentException()
        echo "Recovered. Error:\n", e.msg

    The try block contains the code that might raise an exception. If an exception is raised, the execution immediately jumps to the except block.

  4. In the except block, we use getCurrentException() to get the current exception, and then print its message.

  5. Finally, we call the main procedure:

    main()

When you run this program, it will output:

Recovered. Error:
a problem

The “After mayPanic()” message is not printed because the execution of main stops at the point where the exception is raised and jumps to the except block.

In Nim, exception handling with try-except is similar to other languages like Python or Java. It provides a way to gracefully handle errors and continue execution, which can be crucial for maintaining the stability of long-running programs or services.