func bar: string = ""
func foo() =
let input =
try:
bar()
except:
return
test.nim(6, 10) Error: expression 'bar()' is of type 'string' and has to be discarded
$ nim -v
Nim Compiler Version 1.1.1 [Linux: amd64]
Compiled at 2020-02-24
Copyright (c) 2006-2019 by Andreas Rumpf
git hash: 3dad130034e3212159dda5d61988ca2b18959b24
active boot switches: -d:release -d:useLinenoise -d:nativeStackTrace
It makes sense, as the second branch does not have a definite type. I would write it as
func foo() =
try:
let input = bar()
# do stuff here
except:
return
or (to avoid too much nesting)
func foo() =
var input: string
try:
input = bar()
except:
return
# do stuff here
I understand that the former has the drawback of one more level of nesting per variable, while the latter requires mutable variables that may otherwise not be needed. But the original version is also not very clear in this form
@andreaferretti, The Nim compiler can already make sense of branches that don't produce a value. The following snippet works fine for example:
type
Kind = enum
A
B
C
proc main(k: Kind) =
let x = case k
of A: "a"
of B: "b"
else: raise newException(ValueError, "")
let y = if k == A: "a"
else: raise newException(ValueError, "")
let z = try: "a"
except: raise newException(ValueError, "")
echo x, y, z
main(A)
Producing:
I think it's a pretty good idea to extend this behavior by recognising that return statements produce the same effect.
I can do it. IMO return, break and continue statements can be added to ends in no return definition
Most helpful comment
I can do it. IMO
return,breakandcontinuestatements can be added to ends in no return definition