Every language provides an exception handling to handle exceptions and avoid runtime errors in real time.

Nim Provides the following keywords.

  • try statement
  • Handle exceptions using except
  • finally used to clean up the code
  • raise to throw a custom or Inbuilt exception

NIM Exception handling

The Try block contains code that might throw an exception. The except block allows what happens if the exception is thrown in the try block code In NIM programs,

    // code
except ERROR_TYPE:
    //handle exceptions
    //handle exceptions

    //Clean up code

The try statement contains the try statement keyword followed by a colon(:). The next line to this block contains indented code except contains code to handle exceptions. Multiple except statements are used to handle different exceptions

Here is an exception handler in NIM with an example

proc myprocedure() =
  raise newException(ValueError, "Exception occurred")

except IOError:
    echo("IOError " &

    echo("Default exception " &

    echo "Finally block executes always"


Default exception Exception occurred
Finally block executes always

In the above example,

  • Procedure is created and throws an exception using raise
  • try block contains code to call procedure.
  • multiple except branches declared with IOError and a default exception

Raise Statement

Raise statement used to throw an exception. The exception is either custom or inbuilt exception types.

raise newException(ValueError, "Value Error Occurred")

Exception types in Nim

Exceptions are defined in the System native module.

System.Exception is a Root of all exceptions.

It contains two types of sub types.

  • system.Defect : these are exceptions and terminate the program
  • system.CatchableError : Run time exception

All the above exceptions are inbuilt exceptions.

You can create a Custom exception using type keyword.

  DuplicateRecordError* = object of Exception

DuplicateRecordError is a custom exception that ends with Error.

In the code, you can throw this error using the raise statement.

raise newException(DuplicateRecordError, "Duplicate record found")