ThCxt-ExceptionHandling_emC

ThCxt-ExceptionHandling_emC

Inhalt


Topic:.ExcH.

In C++ (and Java, C# etc) languages the concept of try-catch-throw is established (Exception handling). This is a some more better concept than testing return values of each calling routine or testing errno like it is usual in C. The advantage of try-catch-throw is: Focus on the intrinsically algorithmus. Only in that source where an error may be expected and should be tested for safety operation, the conditions should be tested and a throw should be invoked if the algorithmus does not mastered the situation. And, on the opposite side, in sources where any error in any deeper level may be expected and it is able to handle, a try and catch is proper to write. All levels between try and throw do not regard any exception handling, they are simple. This is the advantage in comparison to the error return concept whereby any level of operation need to test the error return value.

The necessity of handling error return values in C will be often staggered to a later time, because the core algorithm should be fistly programmed and tested. Then, in later time, the consideration of all possible error situations is too much effort to program, it won't be done considering the time line for development ...

Therefore the try-catch-throw concept is helpfull.


1 Never execute faulty instructions, test input arguments

Topic:.ExcH.check.

Last changed: 2019-04

In the following example a routine gets an arrayIndex. The software may be well tested, the arrayIndex has a valid value anytime, so the desire of developer. Nevertheless it should be tested! The test may only be omitted, it the calculation time is very expensive in this case and the routine is defined as static or private in C++. The static definition ensures that only a call in the same source is possible (or included sources, pay attention).

//called level:
int excutesub(..., int arrayIndex, ...) {
  if(arrayIndex > sizeArray || arrayIndex < 0) {
    THROW(IndexOutOfBoundsException, "illegal index", arrayIndex, -1);
    arrayIndex = sizeArray -1;
    faultyData = true;
  }
  myArray[arrayIndex] = ... //access only with correct index!

The THROW statement either invokes throw of C++, longjmp or write a log entry.

In a developer test phase C++ throw should be available while testing the system on a PC platform. Hence the error in runtime is detected, messaged and fixed. For a cheap target system, C++ may not be available or to expensive and longjmp does not work, there is no sensible possibility for error handling. Such an error may be really unexpected, but it is not possible to exclude.

For this case a 'avoidance strategy' is used: The THROW writes only a centralized information for example only one error store, or in a short buffer, and continue. The faulty value is set to a valid value for the safety of working of the system (not a valid value for the correct functionality, it is not possible). The system runs furthermore. The data may be designated as faulty. The system should run furthermore (it should not reseted or such), because other functionality may be work proper and should be work, and a data access for debugging is possible. The error message from THROW can be detected in a maintenance phase.


2 Debugging on runtime

Topic:.ExcH.dbgrun.

The old approach is: Debug any algorithm till it is error-free. That approach cannot be satisfied if the algorithms are complex, the error causing situations are variegated and the time to test is limited.

A better approach may be: Run the system under all possible situations. It is not possible to debug step by step in all such situations.

Therefore the debugging on runtime is the proper approach:


3 Three possibilities of THROW in emC, C++-throw, longjmp and message

Topic:.ExcH.longjmp.

Last changed: 2019-04

The emC programming style knows three levels of using TRY-CATCH-THROW using macros. The user sources itself are not need to adapt for this levels. The macros are adapted. See Chapter: 6 How does it works - Different implementation of the TRY-CATCH-THROW macros.

Generally the THROW can use __FILE__ and __LINE__ in the message to mark the occurrence in source.

The CATCH can contain a stacktrace report from TRY to the THROWing routine. The stacktrace is known from Java, it is a proper instrument for searching the cause.


4 Pattern to write TRY-CATCH-THROW for portable programming

Topic:.ExcH.TRY.

Sources should be tested well on a PC platform where try-catch-throw of C++ is available. Then, without changes, they should run on a target platform where a C-compiler does not have this feature or less footprint is available, and the sources are tested well on the other hand.

The pattern to write sources for that approach is the following one:

void anyOperation() {
  STACKTRC_ENTRY("anyOperation");
  float result;
  TRY {
     //an algorithm which expects errors on calling level
     result = anyOperation();
   }_TRY
   CATCH(Exception, exc) {
     printStackTrace_ExceptionJc(exc, _thCxt);
     log_ExceptionJc(exc, __FILE__, __LINE__);
     //alternate handling on error to continue the operation
     result = 0.0f;
   }
   FINALLY {
     //handling anytime, also if the execption is not catched.
   }
   END_TRY;  //throws an uncatched execption to a higher level.
   //continue outside try
   STACKTRACE_LEAVE;
 }

float anyOperation() {
  STACKTRC_TENTRY("testThrow");
  //...
  CALLINE; throwingOperation();
  STACKTRC_LEAVE; return val;
}
void throwingOperation() {
  STACKTRC_TENTRY("testThrow");
  //any algorithm which
  if(ix >= ARRAYLEN_emC(thiz->array)) { //checks conditions
    THROW_s0(IndexOutOfBoundsException, "msg", ix);
    ix = 0;  //replacement strategy
  }
  STACKTRC_LEAVE
}

There are some situations:

The following ideas are basically:


4.1 Controlling the behavior which strategy of exception handling is used

Topic:.ExcH.TRY.appldef.

It depends on the applstdef_emC.h header file which should used in any source of the application. This file defines:

#define __TRYCPPJc
#include <emC/ThreadContext_emC.h>
#include <emC/Exception_emC.h>

for a C++-using try-catch-throw approach.

#undef __TRYCPPJc
#include <emC/ThreadContext_emC.h>
#include <emC/Exception_emC.h>

for a C-longjmp TRY-CATCH-THROW approach (it works similar)

#include <emC/ExcStacktrcNo.h>

For the simple not try-catch-throw approach with fall-back after a THROW(...) statement.

The last one invokes log_ExceptionJc(...) to write a log. A possible implementation of this routine is contained in emc/source/appl_emC/LogException_emC.c which can be implemented in the given form in a simple target.


4.2 Assembly an error message

Topic:.ExcH.TRY.msg.

The minimal requirement to a logged error is:

A textual value may be a nice to have and maybe an effort on small footprint processors. Therefore it is possible to write such source code fragments in conditionally compiling parts. On the other hand it is a important hint on debugging on runtime (not step by step).

All variants of exception behavior supports an error message which is located in the stack of the throwing level.

Example:

if(faulty) {
  char msg[40] = {0};
  snprintf(msg, sizeof(msg), "faulty index:%d for value %f", ix, val);
  THROW_s0(IndexOutOfBoundsException, msg, ix);

The exception message is prepared using sprintf in the stack area. The THROW_s0 assures that the msg is copied in a safely memory.


5 The ThreadContext to organize Stacktrace

Topic:.StackTrc.

The Stacktrace is used for Exception Handling. If an exception occurs, the information which routine causes it, and from which it was called is an important information to search the reason. This stacktrace mechanism is well known in Java language:

Error script file not found: test\TestCalculatorExpr.jzTc
 at org.vishia.jztxtcmd.JZtxtcmd.execute(JZtxtcmd.java:543)
 at org.vishia.jztxtcmd.JZtxtcmd.smain(JZtxtcmd.java:340)
 at org.vishia.jztxtcmd.JZtxtcmd.main(JZtxtcmd.java:282)

The Stacktrace information may be the most important hint if an error occurs on usage, not in test with debugger. For C language and the emC Exception handling this concept is available too:

IndexOutOfBoundsException: faulty index:10 for value 2.000000: 10=0x0000000A
 at testThrow (src\TestNumericSimple.c:121)
 at testTryLevel2 (src\TestNumericSimple.c:107)
 at testTry (src\TestNumericSimple.c:86)
 at main (src\TestNumericSimple.c:38)

In generally the necessary information about the stack trace can be stored in the stack itself. The entries are located in the current stack level, and the entries are linked backward with a reference to the parent stacklevel. But that concept has some disadvantages:

Therefore the Stacktrace is organized in an extra independent memory area which is static or static after allocation on startup. Its address can be known system wide especially for debugging. This memory is referenced by the ThreadContext memory area which is thread specific and therewith treadsafe.


Topic:.ThCxt.

The ThreadContext concept is a concept of the emC software style which is necessary to hold information about the stack trace for exception handling. Additonally, the ThreadContext provide a mechanism to allocate shortly used dynamic memory, see Chapter: 5.2 A threadlocal heap for short used dynamic memory.


5.1 The availability and structure of the ThreadContext

Topic:.ThCxt._thCxt.


5.1.1 Getting the pointer to the ThreadContext

Topic:.ThCxt._thCxt.getThCxt.

If an operation uses

... myOperation(...) {
  STACKTRC_ENTRY("myOperation");
  ....

which is necessary for the usage of the Stacktrace concept respectively for a Stacktrace entry of this routine, a local variable

struct ThreadContext_emC_t* _thCxt

is available initialized with the pointer to the current ThreadContext. The same is done if the operation has an argument

... myOperation(..., ThCxt* _thCxt) {
  STACKTRC_TENTRY("myOperation");
  ....

The ThCxt is a short form of struct ThreadContext_emC_t per #define. This second form needs this special argument to the subroutine, but the ThreadContext is given immediately.

How the STACKTRC_ENTRY macro gets the ThreadContext reference. In emC/Exception_emC.h is defined:

 #define STACKTRC_ENTRY(NAME) \
   ThCxt* _thCxt = getCurrent_ThreadContext_emC();  STACKTRC_TENTRY(NAME)

The implementation of getCurrent_ThreadContext_emC() depends on the OSAL level for the application and the operation system:

For a simple embedded target without a special operation system with hardware interrupts which do the work, the ThreadContext should be switch between the Interrupt Routine and the back loop. This can be done in a simple form by:

/**Structure for ThreadContexts for Main and 2 Interrupts. */
typedef struct ThCxt_Application_t {

 /**The pointer to the current ThreadContext. */
 ThreadContext_emC_s* currThCxt;

 ThreadContext_emC_s thCxtMain;

 ThreadContext_emC_s thCxtIntr1;

 ThreadContext_emC_s thCxtIntr2;
}ThCxt_Application_s;

/**public static definition*/
ThCxt_Application_s thCxtAppl_g = { &thCxtAppl_g.thCxtMain, { 0 }, { 0 }, { 0 } };

/**A template how to use. */
void interrupt_handler(...) {
 ThreadContext_emC_s* thCxtRestore = thCxtAppl_g.currThCxt;
 thCxtAppl_g.currThCxt = &thCxtAppl_g.thCxtIntr1;
 //the statements of the Interrupt
 thCxtAppl_g.currThCxt = thCxtRestore;
 //end of interrupt
}

Because the interrupt saves the current pointer and restores it, the mechanism is safe also if the other interrupt routine interrupts exact between the 2 statements, get current and set new one. In such a system the exception handling can be established in the interrupt too, it is useful if the algorithm in the interrupt may have throwing necessities.

For such a system the routine

ThreadContext_emC_s* getCurrent_ThreadContext_emC  ()
{
 return thCxtAppl_g.currThCxt;
}

is very simple. The ThreadContext is always the current one stored in the global cell.


5.1.2 Content of the ThreadContext_emC

Topic:.ThCxt._thCxt.ThCxtData.

For the content of the OS_ThreadContext to manage threads see the OSAL-specific implementation of os_thread.c. This chapter only describes the ThreadContext for the user's level.

The following definition is from emc/source/emC/ThreadContext_emC.h. The Headerfile contains comments of course, they are shorten here for a short overview:

typedef struct ThreadContext_emC_t
{
 MemC bufferAlloc;

 /**Up to 30 used addresses for allocated buffers in thread context. */
 AddrUsed_ThreadContext_emC addrUsed[30];

 /**If the bit from 0..29 is set, the address is in use. 0: freed. */
 int32 bitAddrUsed;

 /**The free address of bufferAlloc. It is equal the start address if all is free.*/
 MemUnit* addrFree;
 int16 ixLastAddrUsed;

 int16 mode;

 /**It is the heap, where block heap allocations are provided in this thread. */
 struct BlockHeap_emC_t* blockHeap;

 /**The known highest address in the stack. It is the address of ...*/
 void* topmemAddrOfStack;
 /**Data of the Stacktrace.*/
 StacktraceThreadContext_s stacktrc;
 /*NOTE: The element stacktrc have to be the last
  * because some additional StackEntryJc may be added on end.*/

} ThreadContext_emC_s;

The first 6 elements are for the threadlocal heap. See next Chapter: 5.2 A threadlocal heap for short used dynamic memory. It is a simple concept only for shortly stored informations.

The BlockHeap is another Mechanism for safe non-fragmented dynamic memory, especially for events. See TODO. It is possible to associate such an BlockHead thread-specific.

The data for the StacktraceThreadContext are the last one. Because it is an embedded struct and the definition is static, the number of elements for the Stacktrace can be changed for larger applications by offering a larger memory area. To assert and check that, the pointer to the ThreadContext_emC_s is combined with the size in a MemC struct, see TODO. It will be faulty to calculate the sizeof(ThreadContext_emC_s) if there are more elements. The Stacktrace is defined as (see TODO):

typedef struct StacktraceThreadContext_emC_t

 uint32 zEntries;
 int32 maxNrofEntriesStacktraceBuffer;
 StacktraceElementJc entries[100];

} StacktraceThreadContext_emC_s;


5.1.3 What is happen on the first STACKTRACE_ENTRY("main")

Topic:.ThCxt._thCxt.mainOsInit.

For a System with a OSAL layer for adaption of a multithread operation system, on start of main() is done nothing. The first invocation of getCurrent_ThreadContext_emC) (see Chapter: 5.1.1 Getting the pointer to the ThreadContext) determines that all is uninitialized (code snippet from emc/sourceSpecials/osal_Windows32/os_thread.c:

ThreadContext_emC_s* getCurrent_ThreadContext_emC  ()
{
 OS_ThreadContext* os_thCxt = getCurrent_OS_ThreadContext();
 if(os_thCxt == null){ //only on startup in main without multithreading
   init_OSAL();  //only 1 cause if the ThreadContext haven't set.
   os_thCxt = getCurrent_OS_ThreadContext();  //repeat it
   if (os_thCxt == null) {
     os_FatalSysError(-1, "init_OSAL failed, no ThreadConect", 0,0);
     return null;
   }
 }
 return &os_thCxt->userThreadContext;  //it is a embedded struct inside the whole ThreadContext.
}

Of course the getCurrent_OS_ThreadContext() returns null (it invokes here TlsGetValue(1) from the Windows-API). bOSALInitialized == false too, therefore firstly the OSAL will be initalized. That may be a more complex routine, with some API- and/or Operation System invocations for some Mutex etc.

The advantage to do that on start of main is: A debugging starts at main usually. Another possibility may be: initializing of the OSAL level with a initializer on a static variable.


5.2 A threadlocal heap for short used dynamic memory

Topic:.ThCxt.thrHeap.

Dynamic memory is a basicly problem for embedded long running systems:

Without dynamic memory and without the ThreadContext_emC there are two ways to solve such problems:

Another disadvantage for both approaches are: The length of the buffer is dedicated out of the routine, which determines the content. That causes unflexibility.

Using dynamic memory it is more simple:

char const* myLogPreparer(...) { //prepares and returns a log message
  char* buffer = (char*)malloc(mySize);  //it is static
  snprintf(buffer, mySize, ... //prepare
  return buffer;   //that is ok, because it is allocated.

The calling level should know that the returned pointer should be freed!

But - The usage of dynamic memory may be prohibited.

The ThreadContext provides a mechanism for dynamic memory only for shortly usage and small sizes which solves that problem:

char const* myLogPreparer(...) { //prepares and returns a log message
  STACKTRC_ENTRY("myLogPreparer");   //_thCxt is available
  MemC memb = getUserBuffer_ThreadContext_emC(mySize, "identString", _thCxt);
  char* buffer = PTR_MemC(memb, char);
  snprintf(buffer, mySize, ... //prepare
  STACKTRC_RETURN buffer;   //that is ok, because it is non in stack.
}

The calling routine should invoke:

char const* msg = myLogPreparer(...args for logging...)
free_MemC(msg);

The free_MemC(...) routine checks where the memory is allocated. It frees it correctly for the ThreadContext heap. The freeing should be done immediately in the thread.

If more as one buffer are used from ThreadContext, but all of them are freed in the reverse (or another) order, after freeing the whole ThreadContext heaap is free and therefore not fragmented. The ThreadContext heap is only intended for short-term use.


6 How does it works - Different implementation of the TRY-CATCH-THROW macros

Topic:.ExcH.impl.


6.1 C++ try-catch-throw

Topic:.ExcH.impl..

For C++ the catch statement is contained in the _TRY:

 #define TRY \
 { /*The matching close curly brace is given in the END_TRY at least. */ \
   TryObjectJc tryObject = {NULL_ExceptionJc(), 0}; \
   _thCxt->stacktrc.entries[stacktrace.ix].tryObject = &tryObject; \
   _thCxt->stacktrc.entries[stacktrace.ix].line = __LINE__; \
   try
 .....
 #define _TRY \
 catch(...) { _thCxt->stacktrc.entries[stacktrace.ix].tryObject = null;  \
 if(tryObject.exc.exceptionNr == 0) { /*if 0, a system has occured:*/ \
   tryObject.exc.exceptionNr = tryObject.excNrTestCatch = ident_SystemExceptionJc;  \
   tryObject.exc.exceptionMsg = z_StringJc("System exception"); \
 }  \
 if(false) { /*opens an empty block, closed on the first CATCH macro. */

The common unspecified catch(...) is used from C++. That is because the sophisticated C++ catch mechanism cannot made compatible with the other approaches of TRY-CATCH. The distinction between the exception type is made inside the tryObject. There the THROW writes the exception type info.


6.2 Exception types, distinguish the exception reason

Topic:.ExcH.impl..

The CATCH is defined for C++ as well as for C's longjmp as:

#define CATCH(EXCEPTION, EXC_OBJ) \
   _thCxt->stacktrc.zEntries = stacktrace.ix+1; \
 } else if((tryObject.excNrTestCatch & mask_##EXCEPTION##Jc)!= 0) \
 { ExceptionJc* EXC_OBJ = &tryObject.exc; tryObject.excNrTestCatch = 0;

The first statement of the macro acts as the last statement of the CATCH block above or for the first CATCH as the content of the if(false){ from the _TRY. The substantial function of the CATCH is a if-chain to check exception bits and definition of a local EXC_OBJ.

 #define THROW(EXCEPTION, TEXT, VAL)  throw_sJc(ident_##EXCEPTION##Jc, TEXT, VAL, __LINE__, _thCxt)

The THROW calls an operation with the current source __LINE__ and a constant mask value which determines the exception.

The distinction of the exception reason follows the schema of Java. Java has a more simple exception concept than C++. The exception object is always derived from java.lang.Throwable respectively from the base java.lang.Exception. Some typical exception classes are defined in the core libraries, for example java.lang.IllegalArgumentException or the common java.lang.RuntimeException. The derived exception objects can hold data, but usual only a message as String, the java.lang.ArrayIndexOutOfBoundsException holds a int value, to store the faulty index.

For C usage the concept is simplified again. The ExceptionJc object stores a StringJc, the exception message, a int value and a 1-from-32-bit-value for the exception number. That's all. It is enough to distinguish the exception type (1 of 32 bit) and hold the information to the exception. The mask characteristic of the exception ident value allows association to types of Exception. For example all Exception identificators with one of the bis masked with 0x0fff (12 exception types) is a RuntimeException. That is a simple replacement of the java approach: test instanceof RuntimeException It is a simple but sufficient system.


6.3 C longjmp mechanism

Topic:.ExcH.impl..

The longjmp is a mechanism in C which should only be used to return from a deeper level of subroutine nesting to the higher (calling) level. The setjmp stores the current execution contex in the jmp_buf variable, which is the necessary internal information for the returning longjmp. The longjmp restores the current exeution context, it is the stack frame of the calling routine which the known information in the jmp_buf. See https://en.cppreference.com/w/cpp/utility/program/setjmp. That explaination is correct but it isn't sufficient helpfull. The setjmp function (or macro) has two tasks:

It means, testing the value after setjmp differs whether the setjmp is called by the original code and the execution context was saved to env (citiation from cppreference) or the setjmp routine was invoked from the longjmp (citiation: Non-zero value if a non-local jump was just performed. The return value in the same as passed to longjmp.). It is necessary to invoke longjmp(jmp_buf, value) with a value !=0. That hint is missing on the cppreference page.

The example in the cppreference shows a back jmp to the calling level. Whether or not it is the only one proper action is not documented there. But it is explained in the C99 standard document

citiciation from C99 standard in http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf: ...if the function containing the invocation of the setjmp macro has terminated execution ... in the interim, ..., the behavior is undefined. For standard documents see also https://stackoverflow.com/questions/81656/where-do-i-find-the-current-c-or-c-standard-documents.

Regarding this information the definition to use longjmp is done following:

 #define TRY \
 { TryObjectJc tryObject = {NULL_ExceptionJc(), 0}; \
   _thCxt->stacktrc.entries[stacktrace.ix].tryObject = &tryObject; \
   _thCxt->stacktrc.entries[stacktrace.ix].line = __LINE__; \
   { tryObject.excNrTestCatch = setjmp(tryObject.longjmpBuffer); \
     if(tryObject.excNrTestCatch==0) \
     {

The first 3 lines are the same as in C++ try usage. There were some more { for compiler which cannot define a variable after statements (before C99). The decision about invocation of setjmp (direct or via longjmp) are contained in the excNrTestCatch variable. On ==0 the TRY { block is exected.

 #define _TRY _thCxt->stacktrc.entries[stacktrace.ix].tryObject = null;

The _TRY macro does not contain detection of a asynchron throw event, it is not possible.

#define CATCH(EXCEPTION, EXC_OBJ) \
   _thCxt->stacktrc.zEntries = stacktrace.ix+1; \
 } else if((tryObject.excNrTestCatch & mask_##EXCEPTION##Jc)!= 0) \
 { ExceptionJc* EXC_OBJ = &tryObject.exc; tryObject.excNrTestCatch = 0;

The CATCH macro is exact the same as in C++. The first statement is the last statement of a CATCH before too, it is unnecessary (but not harmful) as last statement of the TRY{ block before. The } else if(... continues the if(...) { from the TRY block, it checks the return value of setjmp.

The THROW macro is the same too. The difference is inside the called throw_sJc(....) routine:

 #if defined(__TRYCPPJc) //&& defined(__cplusplus)
  throw exceptionNr;
 #else
  longjmp(stacktraceTry->tryObject->longjmpBuffer, exceptionNr);
 #endif

There is an difference of the way from the throw to catch and from longjmp to setjmp. The last one goes direct, it restores only the stack context. The throw->catch walks through all subroutine levels and invokes the destructors of all stacklocal objects which are class instances:

 void intermediateLevel(){
   MyClass data;  //invokes default constructor
   ....
 } //on end and on throw the destructor for data is invoked.

Therefore the longjmp approach is not proper for C++, only for C. But respect, ressources opened in intermediate levels are not handled. That is the same as in Java. If it is necessary, a ressource requesting routine should have an own TRY-CATCH block with FINALLY. The FINALLY block is executed anytime, also if the exception is not catched. That is the Java concept too.


6.4 FINALLY and not catched exceptions

Topic:.ExcH.impl.finally.

After the last CATCH block:

CATCH(SpecialException, exc) {
  ....
}
FINALLY {
  //executes it too if CATCH is not executed
}END_TRY

the content of FINALLY is executed any time. It may be important to free ressources on an unexpected error. It is the same behavior like finally in Java.

If the thrown Exception is not catched, no CATCH block is executed, then on END_TRY the a throw is executed with the given exception which can be caught on a higher level.

Here the macros for exeption handling with C++-catch or longjmp:

#define FINALLY \
 /*remove the validy of stacktrace entries of the deeper levels. */ \
 _thCxt->stacktrc.zEntries = stacktrace.ix+1; \
} /*close CATCH brace */\
} /*close brace of whole catch block*/ \
{ { /*open to braces because END_TRY has 2 closing braces.*/


#define END_TRY \
   /*remove the validy of stacktrace entries of the deeper levels. */ \
   _thCxt->stacktrc.zEntries = stacktrace.ix+1; \
  } /*close FINALLY, CATCH or TRY brace */\
 } /*close brace of whole catch block*/ \
 if(tryObject.excNrTestCatch != 0) /*Exception not handled*/ \
 { /* delegate exception to previous level. */ \
  _thCxt->stacktrc.entries[stacktrace.ix].tryObject = null; \
  throw_sJc(tryObject.exc.exceptionNr, tryObject.exc.exceptionMsg, tryObject.exc.exceptionValue, __LINE__, _thCxt); \
 } \
 freeM_MemC(tryObject.exc.exceptionMsg); /*In case it is a allocated one*/ \
 /*remove the validy of stacktrace entries of the deeper levels. */ \
 _thCxt->stacktrc.zEntries = stacktrace.ix+1; \
} /*close brace from beginning TRY*/

If no CATCH is found, or a THROW is invoked without a TRY block, the routine

uncatched_ExceptionJc(&exception, stacktrcThCxt);

is invoked. This should terminate the execution of the thread or the application because nothing is catched.


6.5 TRY, CATCH, THROW macros without exception handling

Topic:.ExcH.impl..

If the software is compiled for a target which should not handle exceptions, because

then the

#include <emC/ExcStacktrcNo_emC.h>

should be included in the applstdef_emC.h header file which is included in all sources. Then the macros are defined in the following form:

#define ThCxt struct ThreadContext_emC_t
/**Because the operation may use a pointer variable named _thCxt it is defined here.
 * But it is initialized with null, because a ThreadContext is unknown, and it is a unknown forward type.
 */
#define STACKTRC_ENTRY(NAME) struct ThreadContext_emC_t* _thCxt = null;
/**For that the _thCxt variable is given in arguments of the operation */
#define STACKTRC_TENTRY(NAME)
#define STACKTRC_LEAVE
#define CALLINE
#define THCXT null
#define TRY
#define _TRY {
/**The catch-code is never executed. With if(false) the compiler may/should optimize it.
 * But define an empty EXC_OBJ because it may be used in the code to compile time.
 */
#define CATCH(EXCEPTION, EXC_OBJ) } { ExceptionJc* EXC_OBJ = null; if(false)
#define FINALLY
#define END_TRY }

Most of the macros are empty. All CATCH blocks are never executed and they can be optimized by the compiler because the static if(false) information. A warning unreachable code should be ignored.

The THROW macro is defined with

#define THROW(EXCEPTION, STRING, VAL)  \
{ ExceptionJc exc = CONST_ExceptionJc(EXCEPTION, STRING, VAL); \
  log_ExceptionJc(&exc, __FILE__, __LINE__);
}
#define THROW_s0(EXCEPTION, TEXT, VAL, ...) \
  THROW(EXCPETION, CONST_z_StringJc(TEXT), VAL)

The THROW_s0 should only be invoked with a const string literal. The routine log_ExceptionJc(...) is invoked by this macro. A possible implementation of this routine is contained in emc/source/appl_emC/LogException_emC.c which can be implemented in the given form in a simple target, or the user can write its own one. At least any hint should be stored in the application.


7 Which moduls are necessary for exception handling and for the simple variant

Topic:.ExcH.example.

The emcTest.zip package contains a TestException directory where 2 Visual Studio 15 projects are contained (with its own solution):

Both projects works with the same source file emcTest/TestException/src/TestException.c. But there have different include paths and compiler options. The TestNoExc needs only 2 additional files:

TestNoExc:

If the string message is not used for logging, the effort can be reduced again for a target with less ressources.

The Exception handling needs some more basic effort:

TestExcHandling:

The os_thread.c is necessary though mulittrheading isn't use here. But the os_ThreadContext is necessary. In another OSAL-constellation especially with only hardware interrupts it is less effort.

The os_file.c depends on the possibility to write the Stacktrace in a file in the ExceptionPrintStacktrace_emC.c. For a system without file system this possibility may be deactivated.