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?

Nitesh Goyal
  • 137
  • 9

2 Answers2

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
jkr
  • 17,119
  • 2
  • 42
  • 68
  • 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. – Nitesh Goyal Apr 20 '20 at 13:08
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.

Lakshitha Wisumperuma
  • 1,574
  • 1
  • 10
  • 17