Panic in Nim

import os

proc main() =
  # We'll use raise throughout this site to check for
  # unexpected errors. This is the only program on the
  # site designed to raise an exception.
  raise newException(Exception, "a problem")

  # A common use of exceptions is to abort if a function
  # returns an error value that we don't know how to
  # (or want to) handle. Here's an example of
  # raising an exception if we get an unexpected error when creating a new file.
  try:
    discard open("/tmp/file", fmWrite)
  except IOError as e:
    raise newException(IOError, "Failed to create file: " & e.msg)

when isMainModule:
  main()

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.

$ nim c -r panic.nim
Error: unhandled exception: a problem [Exception]

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:

Error: unhandled exception: a problem [Exception]
panic.nim(5) panic
system.nim(4069) sysFatal
system.nim(3989) sysFatal

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.