cancel
Showing results for 
Search instead for 
Did you mean: 

Can I implement a software exception handler in C language to simulate a Throw/Catch in Java. This should be available on the Cortex-M4

Dfinn.1
Associate II

The reason for the question is to locate all errors and warnings into a single function so as not to have error handler fuctions located in several places in the code. does anyone have this request previously implemented and can give some input here. thank you

2 REPLIES 2
berendi
Principal

There is setjmp()/longjmp() in C for simple exception handling.​

Le Corre Pierre
Associate III

hi @Dfinn.1​ ,

to go further on setjmp()/longjmp() mentionned by @berendi​ , you can refer to http://www.di.unipi.it/~nids/docs/longjump_try_trow_catch.html.

This works like a charm on STM32WB.

Beware if you use the THROW command inside interrupts! Here is a sample implementation with an example on HardFault_Handler.

/* Credit to http://www.di.unipi.it/~nids/docs/longjump_try_trow_catch.html */
#define TRY do { switch( setjmp(s_jumpBuffer) ) { case 0: while(1) {
#define CATCH(x) break; case x:
#define FINALLY break; } default: {
#define ETRY break; } } }while(0)
#define THROW(x) longjmp(s_jumpBuffer, x)
 
void HardFault_Handler(void)
{
  /* Rewrite manually the stack frame to execute the longjump when exiting the HardFault_Handler. */
  /* Calling THROW(HARDFAULT_EXCEPTION) is not enough as after execution of longjmp we are still in interrupt context. */
  InterruptStackFrame_t *isf = (InterruptStackFrame_t*)__get_MSP(); /* Beware, here we assume the code execute on main stack */
  isf->R0 = (uint32_t)&s_jumpBuffer;
  isf->R1 = HARDFAULT_EXCEPTION;
  isf->ReturnAddress = (uint32_t)longjmp;
}

Hope it can helps.

Pierre.