3

I've made an interface using Boost Python into my C++ code, calling the Python interpreter from my C++ code. I was curious to know if there's any API function or something that can make Python run-time safe. I mean is it possible to make the interpreter skip the faults and errors if any occurred in the code?!

Thanks in advance

Novin Shahroudi
  • 620
  • 8
  • 18
  • 1
    Would it be better practice to simply catch any exceptions within the python code itself? – cm2 Nov 24 '13 at 06:52
  • 1
    "Skipping" a fault or exception isn't an option because it may not be possible for the code to continue to run. Your best bet is to wrap the execution of all Python code in a `try/except` however there's not way to resume and continue at the point it occurred. – martineau Nov 24 '13 at 09:14

1 Answers1

2

Python has exception handling functionality. You can wrap any code that has the potential to create an error in a try block:

 try:
     #do risky stuff
 except Exception as e:
     print "Exception", e, "received. Code will continue to execute"
     #do other stuff that needs to be done

You can replace Exception in that code with a specific type of exception that you're expecting, such as ZeroDivisionError, and then your code will only catch that type of error.

agf
  • 171,228
  • 44
  • 289
  • 238
seaotternerd
  • 6,298
  • 2
  • 47
  • 58
  • 1
    yep, here is a giant thread of all the available options http://stackoverflow.com/questions/730764/try-except-in-python-how-to-properly-ignore-exceptions – user1462442 Nov 24 '13 at 06:53
  • 1
    'Module' has a specific meaning in Python. – agf Nov 24 '13 at 06:56
  • I'm using Python interpreter in my C++ code and I want to do error handling in my c++ code! Handling errors in Python has a drawback that I don't want my c++ errors be handled by Python! – Novin Shahroudi Jan 19 '14 at 17:35
  • If you handle the errors in your C++ code, you won't be able to actually skip over them - you'll have to accept that whatever python function you were trying to run did not successfully executed. That said, the python boost documentation (http://docs.python.org/2/c-api/intro.html#exceptions) makes it look like any error that occurred in the python code should get propagated back to the C++ code, so you can check for it there. – seaotternerd Jan 20 '14 at 05:15