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
Try block contains code that might throw an exception.
except block allows what happens if the exception is thrown in the
try block code
In NIM programs,
try: // code except ERROR_TYPE: //handle exceptions except: //handle exceptions finally: //Clean up code
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") try: myprocedure() except IOError: echo("IOError " & getCurrentExceptionMsg()) except: echo("Default exception " & getCurrentExceptionMsg()) finally: 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
- try block contains code to call procedure.
- multiple except branches declared with IOError and a default exception
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 DuplicateRecordError* = object of Exception
DuplicateRecordError is a custom exception that ends with
In the code, you can throw this error using the
raise newException(DuplicateRecordError, "Duplicate record found")