1

I have a python file (app.py) which makes a call to a function as follows:

answer = fn1()

The fn1() is actually written in C++ and I've built a wrapper so that I can use it in Python. The fn1() can either return a valid result, or it may sometimes fail and terminate. Now the issue is that at the times when fn1() fails and aborts, the calling file (i.e. app.py) also terminates and does not go forward to the error handling part. I would like the calling file to move to my error handling part (i.e. 'except' and 'finally') if fn1() aborts and dumps core. Is there any way to achieve this?

2
  • 3
    What you need to do is to catch the exception in your C++ function and then convert it to a python exception and return that to the python code Commented Apr 20, 2020 at 13:10
  • Added to the answer. Good luck! Commented Apr 20, 2020 at 17:10

2 Answers 2

2

From the OP:

The C++ file that I have built wrapper around aborts in case of exception and dumps core. Python error code is not executed

This was not evident in your question. To catch this sort of error, you can use the signal.signal function in the python standard library (relevant SO answer).

import signal

def sig_handler(signum, frame):
    print("segfault")

signal.signal(signal.SIGSEGV, sig_handler)

answer = fn1()

You basically wrote the answer in your question. Use a try except finally block. Refer also to the Python3 documentation on error handling

try:
    answer = fn1()
except Exception:  # You can use an exception more specific to your failing code.
    # do stuff
finally:
    # do stuff
Sign up to request clarification or add additional context in comments.

1 Comment

I have already done that. But the C++ file that I have built wrapper around aborts in case of exception and dumps core. Python error code is not executed.
1

What you need to do is to catch the exception in your C++ function and then convert it to a python exception and return that to the python code.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.