Nim: Quirky Exceptions don't prevent code to be run after an error.

Created on 19 Feb 2019  路  4Comments  路  Source: nim-lang/Nim

Enabling quirky exceptions with -d:nimquirky and passing input that is not an integer.

import rdstdin, strutils
try:
  let inp = readLineFromStdin("Please enter an integer: ")
  let num = parseInt(inp)
  echo("Correct input of an integer")
except ValueError:
  echo("Input is not an integer; try again")
Please enter an integer: sdh
Correct input of an integer
Input is not an integer; try again

According to the blog post "Quirky Exceptions deal with the question "what code must not be run after an error occured?"" I would expect the lines after parseInt to not run.

Documentation

Most helpful comment

The only reason it got merged was to prevent the implementation from bit rotting. It's not a supported mode of operation. (Yet?) :D

All 4 comments

It may be not obvious, this is the blog post describing quirky exceptions

The only reason it got merged was to prevent the implementation from bit rotting. It's not a supported mode of operation. (Yet?) :D

I learned yesterday that this is not a bug, it's the way, it works.

var s = "2134213we"
var number = 0
try:
   number = parseInt(s)
except:
   # assert(false, "error") # quit(1) in case of error
   # return # or just return
   # number = 0 # or set a default value
   discard
# number has a partial result.
echo number

With this model, you can't use exceptions for control flow, which is something to be avoided anyway. So it really delivers its promise "The programmer remains in control over the control flow". Also allows to prove the program correct (see course "LAFF-On Programming for correctness" and topic "Hoare Logic").

Note that assert is still treated as a programming bug and will terminate execution of the program.
If you need to set a default value in case of an error, it is still trivial. I like this, so +1.

@b3liever For -d:nimQuirky I think the IO operations should check whether there is an "active" error and then return immediately, otherwise it's just too weird. :-)

Was this page helpful?
0 / 5 - 0 ratings

Related issues

zzz125 picture zzz125  路  4Comments

koki-koba picture koki-koba  路  3Comments

juancarlospaco picture juancarlospaco  路  3Comments

capocasa picture capocasa  路  3Comments

timotheecour picture timotheecour  路  3Comments