Panic in Nim
In Nim, we use exceptions to handle unexpected errors, which is similar to panics in other languages. The raise
keyword is used to throw an exception.
Running this program will cause it to raise an exception, print an error message and stack trace, and exit with a non-zero status.
When the first exception in main
is raised, the program exits without reaching the rest of the code. If you’d like to see the program try to create a temp file, comment out the first raise
statement.
Note that unlike some languages which use exceptions for handling of many errors, in Nim it’s idiomatic to use error-indicating return values (like Option
or Result
types) wherever possible, and use exceptions for truly exceptional situations.
In Nim, exceptions provide stack traces by default:
This output shows the file and line number where the exception was raised, as well as the call stack.
Remember that while exceptions can be useful for handling truly unexpected errors, it’s generally better to use error-handling mechanisms like Option
or Result
types for expected error conditions in Nim.