Python/SWIG TypeError - c++

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?

Related

How to handle the "out of range" exception in C++ when implementing a nd-array

I was trying to implementing a nd-array in C++ like numpy in python, but I do not know how to handle the problems(or exceptions?) like "indices out of range". Should I just use the assert to check the parameters at the beginning of the functions, or use try/catch/throw mechanisms?
BTW, if I use assert, how to print the error messages like "the input index is out of range" to users instead of just "assert at line 5 failed" assertions.
the macro I am using right now to check the index:
#define RANGE_CHECK(total, index) assert(total > index)
The method used by the standard library is to throw std::out_of_range, from functions named at, and to have undefined behaviour in functions named [].
Asserts are for things that never ever should happen and the only way to handle them is to terminate the program. Basically you never ever want to use them (although sometimes it's the only way).
So go with exceptions. The std lib already has a number of excpetions defined that you can throw for stuff like index out of range. Use them.
With exceptions the default will be to terminate the program, just like with assert. But unlike an assert the program can try/catch the exception and handle the error if they like. It's then their job to print a more meaningfull error message if they so desire.
C++ is the world of lazy programmers; they normally tend to stay off exception handling as long as possible. As #Caleth mentioned earlier, following std conventions, one can provide a none-throwing operator[] as well as a throwing at. But boosters proposed a postponed exception-handling approach throughout either of the following:
std::optional:
Return a std::optional<T> instead of T:
std::optional<T*> arr::at(size_t)noexcept;
Provide a none-throwing overload - alongside the throwing function - with an extra std::error_condition reference argument:
`T* arr::at(size_t) throw(std::out_of_range);
T* arr::at(size_t, std::error_condition &ec) noexcept;`
return a pair of value and std::error_condition:
std::pair<T*,std::error_condition> arr::at(size_t)noexcept;

How to make Python runtime safe?

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.

Shedskin - Compile Error

I'm currently trying to compile a python project (5files # total 1200 lines of code) with shedskin.
I tried shedskin Version 0.9.3 and 0.9.2 both result in the same errors.
This is the first error I encounter:
mmain.cpp: In function ‘__shedskin__::list<__shedskin__::list<int>*>* __mmain__::list_comp_3(__shedskin__::__ss_int)’:
mmain.cpp:133: error: no matching function for call to ‘__shedskin__::list<__shedskin__::list<int>*>::append(__shedskin__::list<double>*)’
Moreover, I after running shedskin (i.e. before typing "make") I receive many warnings - all related to dynamic types:
*WARNING* mmain.py: expression has dynamic (sub)type: {float, int, list}
However, shedskin seems to work flawlessly with the provided examples since I can compile and execute them without any errors.
Do you have an idea where to look for the error or what the error is related to?
mmain.cpp:133: error: no matching function for call to ‘__shedskin__::list<__shedskin__::list<int>*>::append(__shedskin__::list<double>*)’
This error means that you've got a Python object that shedskin has inferred as a list of lists of ints, but now you're trying to append something that it's inferred as a list of floats. You can get that by, for example, doing this:
a = [[1], [2]]
b = 1.0
a.append([b])
However, from the line above it, the function name is list_comp_3. Unless you've actually named a function list_comp_3 (which you haven't), this is a list comprehension. So, you may be doing something like this:
a = [1, 2, 3.0]
b = [[i] for i in a]
You may be wondering why it let you get away with a but failed on b. Well, first of all, it probably didn't really let you get away with it, if you've got dozens of warnings you haven't dealt with. But second, as the documentation says:
Integers and floats can often be mixed, but it is better to avoid this where possible, as it may confuse Shed Skin:
a = [1.0]
a = 1 # wrong - use a float here, too
As for the warnings, they can mean anything from "you got away with it this time, but don't expect to always do so" to "an error is coming up related to this" to "this will compile, but to something less efficient than the original Python code rather than more" to "this will compile, but to something incorrect".
More generally, it sounds like your program just can't be statically typed by shedskin's inference engine. Without actually seeing your code, it's impossible to tell you what you're doing wrong, but if you re-read the Typing Restrictions and Python Subset Restrictions sections of the docs, that should give you ideas of what kinds of things are and aren't appropriate.
to avoid confusion, please note that both code snippets provided by 'abartert' compile and run fine when compiled separately (shedskin 0.9.3). my guess is also that the problem should disappear after resolving the dynamic typing warnings. if not, I'd be very interested in seeing the program you are trying to compile, or at least enough of it to reproduce the problem.
update: btw, as of 0.9.1 or so, shedskin should be smarter about int and float mixing. if it encounters something that would lead to broken or inefficient c++ code (because of necessary run-time conversion of sorts), it should now usually complain with an 'incompatible types' warning. so perhaps it's time to update this part of the documentation slightly for 0.9.3.

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!");

In C++ what are the benefits of using exceptions and try / catch instead of just returning an error code?

I've programmed C and C++ for a long time and so far I've never used exceptions and try / catch. What are the benefits of using that instead of just having functions return error codes?
Possibly an obvious point - a developer can ignore (or not be aware of) your return status and go on blissfully unaware that something failed.
An exception needs to be acknowledged in some way - it can't be silently ignored without actively putting something in place to do so.
The advantage of exceptions are two fold:
They can't be ignored. You must deal with them at some level, or they will terminate your program. With error code, you must explicitly check for them, or they are lost.
They can be ignored. If an error can't be dealt with at one level, it will automatically bubble up to the next level, where it can be. Error codes must be explicitly passed up until they reach the level where it can be dealt with.
The advantage is that you don't have to check the error code after each potentially failing call. In order for this to work though, you need to combine it with RAII classes so that everything gets automatically cleaned up as the stack unwinds.
With error messages:
int DoSomeThings()
{
int error = 0;
HandleA hA;
error = CreateAObject(&ha);
if (error)
goto cleanUpFailedA;
HandleB hB;
error = CreateBObjectWithA(hA, &hB);
if (error)
goto cleanUpFailedB;
HandleC hC;
error = CreateCObjectWithA(hB, &hC);
if (error)
goto cleanUpFailedC;
...
cleanUpFailedC:
DeleteCObject(hC);
cleanUpFailedB:
DeleteBObject(hB);
cleanUpFailedA:
DeleteAObject(hA);
return error;
}
With Exceptions and RAII
void DoSomeThings()
{
RAIIHandleA hA = CreateAObject();
RAIIHandleB hB = CreateBObjectWithA(hA);
RAIIHandleC hC = CreateCObjectWithB(hB);
...
}
struct RAIIHandleA
{
HandleA Handle;
RAIIHandleA(HandleA handle) : Handle(handle) {}
~RAIIHandleA() { DeleteAObject(Handle); }
}
...
On first glance, the RAII/Exceptions version seems longer, until you realize that the cleanup code needs to be written only once (and there are ways to simplify that). But the second version of DoSomeThings is much clearer and maintainable.
DO NOT try and use exceptions in C++ without the RAII idiom, as you will leak resources and memory. All your cleanup needs to be done in destructors of stack-allocated objects.
I realize there are other ways to do the error code handling, but they all end up looking somewhat the same. If you drop the gotos, you end up repeating clean up code.
One point for error codes, is that they make it obvious where things can fail, and how they can fail. In the above code, you write it with the assumption that things are not going to fail (but if they do, you'll be protected by the RAII wrappers). But you end up paying less heed to where things can go wrong.
Exception handling is useful because it makes it easy to separate the error handling code from the code written to handle the function of the program. This makes reading and writing the code easier.
return an error code when an error condition is expected in some cases
throw an exception when an error condition is not expected in any cases
in the former case the caller of the function must check the error code for the expected failure; in the latter case the exception can be handled by any caller up the stack (or the default handler) as is appropriate
Aside from the other things that were mentioned, you can't return an error code from a constructor. Destructors either, but you should avoid throwing an exception from a destructor too.
I wrote a blog entry about this (Exceptions make for Elegant Code), which was subsequently published in Overload. I actually wrote this in response to something Joel said on the StackOverflow podcast!
Anyway, I strongly believe that exceptions are preferable to error codes in most circumstances. I find it really painful to use functions that return error codes: you have to check the error code after each call, which can disrupt the flow of the calling code. It also means you can't use overloaded operators as there is no way to signal the error.
The pain of checking error codes means that people often neglect to do so, thus rendering them completely pointless: at least you have to explicitly ignore exceptions with a catch statement.
The use of destructors in C++ and disposers in .NET to ensure that resources are correctly freed in the presence of exceptions can also greatly simplify code. In order to get the same level of protection with error codes you either need lots of if statements, lots of duplicated cleanup code, or goto calls to a common block of cleanup at the end of a function. None of these options are pleasant.
Here's a good explanation of EAFP ("Easier to Ask for Forgiveness than Permission."), which I think applies here even if it's a Python page in Wikipedia. Using exceptions leads to a more natural style of coding, IMO -- and in the opinion of many others, too.
When I used to teach C++, our standard explanation was that they allowed you to avoid tangling sunny-day and rainy-day scenarios. In other words, you could write a function as if everything would work ok, and catch the exception in the end.
Without exceptions, you would have to get a return value from each call and ensure that it is still legitimate.
A related benefit, of course, is that you don't "waste" your return value on exceptions (and thus allow methods that should be void to be void), and can also return errors from constructors and destructors.
Google's C++ Style Guide has a great, thorough analysis of the pros and cons of exception use in C++ code. It also indicates some of the larger questions you should be asking; i.e. do I intend to distribute my code to others (who may have difficulty integrating with an exception-enabled code base)?
Sometimes you really have to use an exception in order to flag an exceptional case. For example, if something goes wrong in a constructor and you find it makes sense to notify the caller about this then you have no choice but to throw an exception.
Another example: Sometimes there is no value your function can return to denote an error; any value the function may return denotes success.
int divide(int a, int b)
{
if( b == 0 )
// then what? no integer can be used for an error flag!
else
return a / b;
}
The fact that you have to acknowledge exceptions is correct but this can also be implemented using error structs.
You could create a base error class that checks in its dtor whether a certain method ( e.g. IsOk ) has been called. If not, you could log something and then exit, or throw an exception, or raise an assert, etc...
Just calling the IsOk on the error object without reacting to it, would then be the equivalent of writing catch( ... ) {}
Both statement would display the same lack of programmer good will.
The transport of the error code up to the correct level is a greater concern. You would basically have to make almost all methods return an error code for the sole reason of propagation.
But then again, a function or method should always be annotated with the exceptions it can generate. So basically you have to same problem, without an interface to support it.
As #Martin pointed out throwing exceptions forces the programmer to handle the error. For example, not checking return codes is one of the biggest sources of security holes in C programs. Exceptions make sure that you handle the error (hopefully) and provide some kind of recover path for your program. And if you choose to ignore an exception rather than introduce a security hole your program crashes.