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,
try:
// code
except ERROR_TYPE:
//handle exceptions
except:
//handle exceptions
finally:
//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")
try:
myprocedure()
except IOError:
echo("IOError " &
getCurrentExceptionMsg())
except:
echo("Default exception " &
getCurrentExceptionMsg())
finally:
echo "Finally block executes always"
Output:
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 a custom or inbuilt exception type.
raise newException(ValueError, "Value Error Occurred")
Exception types in Nim
Exceptions are defined in the System
native module.
System.Exception
is the Root of all exceptions.
It contains two types of subtypes.
system.Defect
: these are exceptions and terminate the programsystem.CatchableError
: Run time exception
All the above exceptions are inbuiltQ.
You can create a Custom exception using the type
keyword.
type
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")