I was surprised that the following line does not parse:
_
_ _ _(_)_ | Documentation: https://docs.julialang.org
(_) | (_) (_) |
_ _ _| |_ __ _ | Type "?" for help, "]?" for Pkg help.
| | | | | | |/ _` | |
| | |_| | | | (_| | | Version 1.11.6 (2025-07-09)
_/ |\__'_|_|_|\__'_| | Official https://julialang.org/ release
|__/ |
julia> try 1 catch e1 (-Inf) end
ERROR: ParseError:
# Error @ REPL[1]:1:12
try 1 catch e1 (-Inf) end
# ββββββββββ ββ a variable name is expected after `catch`
Stacktrace:
[1] top-level scope
@ none:1
julia>
Can anyone explain why this fails and what would be the best working alternative? My best working alternative so far is:
try 1 catch e1 Inf * (-1) end
I would prefer a one line solution.
You can just use semicolons:
julia> try 1; catch e1; (-Inf); end
1
2 Likes
Use semicolons to separate statements if you donβt want literal line breaks
julia> try 1; catch e1; -Inf; end
1
julia> try error(); catch e1; -Inf; end
-Inf
EDIT: too slow
2 Likes
I had a vague memory of most control-flow blocks in Julia requiring new-line or ;
to work, but the following works fine (julia v1.11.6):
if true print("true") else print("false") end
for x in 1:3 println("hello") end
Not sure if there is some specific reason that the try-catch block specifically does not behave the same.
1 Like
The issue is when there is parsing ambiguity on where one expression ends and another begins:
julia> for x in 1:3 x |> println end
1
2
3
julia> for x in 1:3 +x |> println end # parse as `for x in (1:(3+x) |> println) end`
ERROR: UndefVarError: `x` not defined in `Main`
julia> x = 4;
julia> for x in 1:3 +x |> println end # parse as `for x in (1:(3+x) |> println) end`
1:7
ERROR: MethodError: no method matching iterate(::Nothing)
3 Likes
For it to make sense in the OP, not just ambiguous statements but also βtoo close for comfortβ statements are not allowed, because
julia> e1 (-Inf)
ERROR: ParseError:
# Error @ REPL[8]:1:3
e1 (-Inf)
# β ββ whitespace is not allowed here
Stacktrace:
[1] top-level scope
@ none:1
julia>
is not ambiguous.
Whatever the reason, using semicolon is a good solution, it even allows making the statement shorter:
try 1 catch; -Inf end