Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Python-style catch statement works but is misleading #51031

Open
LilithHafner opened this issue Aug 23, 2023 · 2 comments
Open

Python-style catch statement works but is misleading #51031

LilithHafner opened this issue Aug 23, 2023 · 2 comments
Labels
error handling Handling of exceptions by Julia or the user

Comments

@LilithHafner
Copy link
Member

It is unfortunate that the standard python try-catch style works fine in Julia but silently catches too much

>>> try:
...     foo
... except NameError:
...     print("Got a name error")
... 
Got a name error

julia> try
           foo
       catch NameError
           println("Got a name error")
       end
Got a name error

See JuliaStats/Statistics.jl#147 (comment) for an example of this in the wild (in a stdlib, my fault)

@brenhinkeller brenhinkeller added the error handling Handling of exceptions by Julia or the user label Aug 23, 2023
@Seelengrab
Copy link
Contributor

Seelengrab commented Aug 24, 2023

I'm not sure if this behavior is explicitly documented (https://docs.julialang.org/en/v1/manual/control-flow/#Exception-Handling) or not (it certainly "leaks through", but could be more explicit), but a good way to make this "work" automatically could be by supporting something like

try
    foo
catch e::NameError
    println("got a name error: $e")
end

or

try
    foo
catch ::NameError
    println("got a name error")
end

to do the equivalent of

try
    foo
catch e
    e isa NameError || rethrow(e)
    println("got a name error: $e")
end

In the short term though, adding an explicit warning to the docs is probably best.

@KristofferC
Copy link
Member

The docs say:

 The syntax `catch e` (where `e` is any variable) assigns the thrown exception object to the given variable within the catch block.

so it is pretty clear what this does. Adding it to the Noteworthy Language differences is probably a good idea though.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
error handling Handling of exceptions by Julia or the user
Projects
None yet
Development

No branches or pull requests

4 participants