[Solved]Catch exception raised in C in python
Posted: Tue Oct 02, 2018 2:40 pm
Hi.
I just read an (old) thread about this topic (viewtopic.php?f=2&t=178) which seems to indicate that it is possible to 'catch' an 'exception' in a python try-except block that is raised in C.
However i am not able to reproduce that nor do I understand how to get it working.
The original thread use an MP_RAISE macro around nlr_raise, which as the original thread points out just is a setjmp/longjmp (to where nlr_push was done).
In my case this is in execute_from_string (based on the demo code), so it is outside of the mp_call_function_0 which i used to start the python code.
I don't see how with I can change this mechanism to end up in try block at python level similar to the dhtest.py example from the original thread. Was this possible in older versions but not anymore ? Should i use something else than the nlr_raise based functions (mp_raise_msg & co) ? Did I misunderstand the original thread ?
Thanks
Bram
I just read an (old) thread about this topic (viewtopic.php?f=2&t=178) which seems to indicate that it is possible to 'catch' an 'exception' in a python try-except block that is raised in C.
However i am not able to reproduce that nor do I understand how to get it working.
The original thread use an MP_RAISE macro around nlr_raise, which as the original thread points out just is a setjmp/longjmp (to where nlr_push was done).
In my case this is in execute_from_string (based on the demo code), so it is outside of the mp_call_function_0 which i used to start the python code.
Code: Select all
if (nlr_push(&nlr) == 0)
{
qstr src_name = MP_QSTR_;
mp_lexer_t *lex = mp_lexer_new_from_str_len( src_name, str, strlen(str), false);
mp_parse_tree_t pt = mp_parse(lex, MP_PARSE_FILE_INPUT);
mp_obj_t module_fun = mp_compile(&pt, src_name, MP_EMIT_OPT_NONE, false);
mp_call_function_0(module_fun);
nlr_pop();
return 0;
} else {
//exception handling code, C level
...
}
Thanks
Bram