How to make Python runtime safe? - c++

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

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.

Related

Turn on stack traces for exceptions in bucklescript

I'm trying to port some OCaml tests from OUnit2 to bs-jest, but I get a Not_found exception raised from some test and I don't know where it's coming from; is there a way to enable stack traces in bucklescript?
In OCaml, I would pass the -g option to the compiler, but it doesn't seem to do anything when calling bsc. When an exception is thrown and not caught the program just crashes with no info, and when I catch it and use say Printexc.get_backtrace I get the message "(Program not linked with -g, cannot print stack backtrace)".
BuckleScript exception handling is a bit weird. Try using the techniques suggested here to replace your exceptions with BS-style exceptions.

Can I throw an error in c code just like Rcpp's stop() in Julia

In my origin C++ code, I use assert(), but if I want to use this code in Julia, maybe I need to replace it with other functions. In R, I can use Rcpp::stop(). Is there any easy way to do it in Julia with C or C++ code.
And it seems that Julia does not have R CMD check like stuff yet. It does not check this kind of issue.
Thanks.
The question here is what you want to achieve.
If assert() fits your purpose in C, you can use that in code called from Julia as well. Note that your julia session will be aborted if an error occurs, but if it is to indicate a programming error in your C code, that is probably totally fine.
If you want your Julia code to be able to programmatically handle the error condition (and get an exception in Julia), you need to use standard C-api practices, and return an error code from the entry point. After the ccall, you can check the error code and throw an exception in Julia. jl_error() is not recommended to use unless you write some very Julia specific C code.
In C++, you can throw some exception, e.g. std::runtime_error like
throw std::runtime_error("bad error");
Read a lot more about how C++ handle exceptions (with all the intermediate nested destructors automagically invoked).
In C code, you might use longjmp to come back to some point in your main loop (or main program), at some use of setjmp(3). Use it with great caution and read several things about it. The usual practice in C is to use error codes (like most C library functions do) and propagate them manually (or simply, abort or exit(EXIT_FAILURE) with some fatal message, maybe using perror)
Read also about embedding Julia, Calling C & Fortran code from Julia and notice its jl_error thing.

Python/SWIG TypeError

I've created a simple SWIG helper function to deal with the pointers returned from the C++ code I've wrapped:
//in module foo:
%inline %{
double getPtrVal(double *ptr, int i) {
return (double) ptr[i];
}
%}
This worked fine until I tried something like:
for i in range(n):
for j in range(n):
val = foo.getPtrVal(ptrs, i)
at which point Python returned with a TypeError, complaining that n wasn't an integer:
for i in range(n):
TypeError: an integer is required
I assure you that n is, in fact, an integer (type(n) consistently returns <type 'int'>). Thus, I believe the problem lies somehow in the SWIG function. The strange thing is that foo.getPtrVal(ptrs, i) is called n times without issue, then, immediately after exiting the inner loop over j for the first time, the error is thrown. Any ideas? I could post further code segments if it would clarify parts. Thanks!
I've run into a similar problem before. If some part of your SWIG C wrapper code is not properly cleaning up Python's internal exception state, then the very next builtin call capable of raising an exception in your Python code will appear to be the source of the exception.
range can raise exceptions, so Python inspects its internal exception state after calling it, sees the exception left over from your SWIG C wrapper code, and assumes that it must have come from range.
When I couldn't fix such a problem I used this ugly workaround to clear the internal exception state:
try:
sys.stdout.write("") # any call capable of raising an exception will do
except:
pass
The proper way might be with an %exception directive; see the SWIG manual. But you need to figure out which call is causing the exception, first.
Did actual code have missing colon?

Exception is not caught although it is included in catch statement

I have this program written in C++ Builder 6. I didn't write all the code, just some of it. The language, however, is not C++ (as far as I'm aware) - it looks more like Delphi or Pascal. So that's why I included them all in the tags.
I have an int called Oversteering.
try
{
Oversteering=HoursCounter.ToInt();
}
catch(EConvertError &convertError)
{
Oversteering=0;
}
HoursCounter is an AnsiString, and it is in the form of an int.
Since this is the only try/catch statement in the whole code (that's not too good, I know), and I couldn't find any good example of such in Delphi/Pascal/???, I don't know if it's correctly written.
Well, I try to convert the string to an int. Sometimes I get this error:
That is, an exception called EConvertError has occurred.
So my question is: why is this exception NOT caught by the catch statement?
This error is shown by the debugger when running through the code,
if you run the exe and have the same situation the error message will not be shown to you
The exception is caught but the debugger is notifiying you regarding the error in the code
that is here
try
{
Oversteering=HoursCounter.ToInt();
}
since running in the debugger the ,your trying to convert (blankspace) '' to integer, the debugger will show the exception...but when running the exe, the debugger will set
Oversteering=0
check this from about.com
Break On Exceptions
When building a program with exception handling, you may not want Delphi to break on Exceptions. This is a great feature if you want Delphi to show where an exception has occurred; however, it can be annoying when you test your own exception handling.
As #PresleyDias explained, it is the debugger that is displaying the exception, not your app. The exception is being caught (you should be catching it by a const reference, though), but the debugger sees it before your app does, that's all. You can configure the debugger to ignore EConvertError, if you like.
A better solution is to avoid the exception in the first place. If you use AnsiString::ToIntDef() instead, you can remove the try/catch block completely:
Oversteering = HoursCounter.ToIntDef(0);
Alternatively, you can use TryStrToInt() instead:
if (!TryStrToInt(HoursCounter, Oversteering))
{
...;
}
If 0 is a valid value for your counter, use TryStrToInt():
if (TryStrToInt(HoursCounter, Oversteering))
{
// use Oversteering as needed, even zeros...
}
else
ShowMessage("Cannot convert HoursCounter to a valid integer!");
If 0 always represents an error, then use ToIntDef():
Oversteering = HoursCounter.ToIntDef(0);
if (Oversteering != 0)
{
// use Oversteering as needed, except zeros...
}
else
ShowMessage("Cannot convert HoursCounter to an acceptable integer!");

Uncaught exception in a callback from a 3rd party static library

I am compiling my program with a 3rd party library. That library contains an error callback if an error occurs internally. Inside that error callback I am throwing an exception and I have a unit test to verify that when I do something invalid that the exception is thrown. This all works beautifully in Windows, but when I test this in linux (fedora) I am getting an abort from an uncaught exception.
I tried wrapping my call directly with a try-catch block but no luck. ( Also, all my code is running within the google test framework which also normally catches exceptions ). The only thing that seems to catch the exception is if I wrap the throw statement in a try block directly within the error callback.
Does anyone have any idea why this would happen and if there is a way to catch the exception?
When you interface with third-party libraries you usually have to catch all exception on the border between your code and their code:
int yourCallback( params )
{
try {
doStuff( params );
return Okay;
} catch (...) {
return Error;
}
}
The reason is you can't be sure that library is written in C++ or it uses the very same version of C++ runtime as your code uses.
Unless you're completely sure that code can deal with your exceptions you can't propagate exceptions to third-party code. The extreme example is COM where both your code and "other code" can be in whatever language and with whatever runtime and you are not allowed to let exceptions propagate through COM boundary.
Usually you should not throw exceptions "through" code you do not know anything about. It might be C code, which will not even clean up after itself.
How to deal with your concrete problem would require concrete information about the 3rd-party library you are interfacing with. What is that callback there for? To give you a chance to fix stuff? To inform you that an error occurred? Can you cancel whatever operation it is called from?
One way to deal with such a scenario is to store some information somewhere when the callback is called and check for that information when the actual processing finishes from your function that calls into that library.