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:
We import the
strutils
module, which provides string handling utilities.We define a
mayPanic
procedure that raises an exception:proc mayPanic() = raise newException(Exception, "a problem")
In the
main
procedure, we use atry
-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 theexcept
block.In the
except
block, we usegetCurrentException()
to get the current exception, and then print its message.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.