The error is not caught with try block in Nim

Viewed 119

The error will be thrown because wrong CSV row accessed, but the error won't be catched by try block. Why, and how to catch it?

import parsecsv

# Prepare a file
let content = """One,Two,Three,Four
1,2,3,4
10,20,30,40
100,200,300,400
"""
writeFile("temp.csv", content)

var p: CsvParser
p.open("temp.csv")
p.readHeaderRow()
while p.readRow():
  try:
    echo p.rowEntry("wrong") # <= Error here
  except:
    echo "error"
p.close()

The error

$ nim c -r run.nim 
Traceback (most recent call last)
/alex/projects/run.nim(33) run
SIGSEGV: Illegal storage access. (Attempt to read from nil?)
Error: execution of an external program failed: '/alex/projects/run '
2 Answers

If you import the segfaults module, this type of error can be caught. I assume it isn't imported by default for performance reasons.

Why it's an error in the first place is less clear. Strings used to be nilable in Nim, so I assume at the time parsecsv.rowEntry was written, it would return nil, which you could then check for. This isn't possible anymore, so the proc should probably be updated to raise an error. I'll look into it.

As stated in the documentation:

## `parser.rowEntry("NotExistEntry")` causes SIGSEGV fault.

Your headers are stored in p.headers so you can "catch" the error with code written like this:

var p: CsvParser
p.open("temp.csv")
p.readHeaderRow()
while p.readRow():
  if "wrong" in p.headers:
    echo p.rowEntry("wrong")
  else:
    echo "error"
Related