JuliaPy / PythonCall.jl

Python and Julia in harmony.
https://juliapy.github.io/PythonCall.jl/stable/
MIT License
720 stars 61 forks source link

PythonCall.jl how do I handle Python exceptions? #388

Open hubert-associates opened 8 months ago

hubert-associates commented 8 months ago

Using PythonCall.jl, how do I best handle python exception patters such as the following python:

try:
  database = client.create_database(DATABASE_NAME)
except exceptions.CosmosResourceExistsError:
  database = client.get_database_client(DATABASE_NAME)

xref stackoverflow

cjdoris commented 8 months ago

This in Julia

julia> try
           @pyexec "raise ValueError('foo')"
       catch err
           if err isa PyException && pyisinstance(err, pybuiltins.ValueError)
               @info "handling a ValueError"
           else
               rethrow()
           end
       end
[ Info: handling a ValueError

is roughly equivalent to this in Python

>>> try:
...     raise ValueError('foo')
... except ValueError as err:
...     print('handling a ValueError')
...
handling a ValueError
hubert-associates commented 8 months ago

Sincere thanks for the quick response. Tricky/frustrating to arrive here without this user's guide pattern ....