3

I am wrapping a C lib to python module using SWIG. But exception does not seem to be raised at the right place, I have a simple demo for this,

except_test.i

%module except_test


%{
#include "except_test.h"
#include <stdio.h>
%}

%{
static int flagged_exception = 0;

void throw_except()
{
    flagged_exception = 1;
    printf("flag set \n");
}
%}

%exception {
    $action
    printf("exception block\n");
    if (flagged_exception) {
        printf("before setstring\n");
        PyErr_SetString(PyExc_RuntimeError, "test except");
        printf("after setstring\n");
        flagged_exception = 0;
    }
}
%include "except_test.h"

except_test.c

#include "except_test.h"


int except_test(int a) {

    if (a < 0) {
        throw_except();
        return 0;
    } else{
        return -1;
    }
}

run_except.py

from except_test import *
import time

def test():
    b = except_test(-1)
    print 'b=', b

try:
    test()
except:
    print "caught exception"

for i in range(10):
    print i
    time.sleep(1)

Now if I run run_except.py

$python run_except.py 
flag set 
exception block
before setstring
after setstring
b= 0
0
Traceback (most recent call last):
  File "run_except.py", line 15, in <module>
    time.sleep(1)
RuntimeError: test except

as the output shows, the try/catch block didn't catch the exception. Why is this? and How to avoid this?

Thanks,

1
  • Look at the generated code in _wrap.c file. Is the code in %exception there?
    – Oliver
    Dec 20, 2013 at 23:25

2 Answers 2

4

You have to return NULL from a Python extension to have it notice the error immediately:

if (flagged_exception) {
    PyErr_SetString(PyExc_RuntimeError, "test except");
    flagged_exception = 0;
    return NULL;
}

But using the generic SWIG macros will make the SWIG interface more portable to other languages.

2

You need to put SWIG_fail; right after PyErr_SetString. Alternatively, there is a convenient (and what's more important language-independent) macro SWIG_exception(SWIG_RuntimeError, "error message") wrapping PyErr_SetString and SWIG_fail.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.