Pycall, Exception Handling of Python errors with Julia's `try-catch`

Assuming I have the following python code:

import module as m

try:
    # do something
except (m.SomeError, ValueError) as err:
    # do other stuff

And that I want to write it in Julia using PyCall, starting with:

using PyCall

m = pyimport("module")

How can I use Julia’s try-catch statement to achieve the same result as in the Python code? In other words, I want to catch m.SomeError and ValueError in Julia.

As far as I remember, all Python exceptions are wrapped into a single Julia exception type by PyCall.
But you can still do your Python specific error handling in Python, e.g.

py"""
def my_func(x):
    try:
        # do something
    except (m.SomeError, ValueError) as err:
        # do other stuff
    return result"""
my_func = py"my_func" # assign a Julia name
my_func(z)

To signal an error state of the Python function, you may pass a sentinel value (e.g. None) to Julia.

PyCall wraps Python errors in a PyError type when you catch an exception err, but you can extract the underlying Python error class with err.T and the error instance with err.val.

So, for example, you could do something like:

m = pyimport("module")
try
    # do something
catch err
    if err isa PyCall.PyError && err.T in (m.SomeError, py"ValueError")
        # do other stuff
    end
end
2 Likes

Thanks, that’s exactly what I wanted.