PFL Exception Handling

Wednesday, 11 November 2026 16:20 UTC

PFL provides a mechanism to track exceptions with stack tracing. It works similarly to Java, Python and C++ but is designed to be more efficient in terms of memory allocation and performance overhead.

The problem with Exceptions is that they tend to be less exceptional that the name would suggest. For example, consider parsing a string that is expected to contain a valid representation of an integer. It is common to just try to convert it and then check if the converter function raises an exception. This exception would typically result in a stack-trace object being created on the heap, possibly including a series of additional objects, each representing a line of the call stack. This is potentially a lot of memory allocation and system calls just to return what could have been a boolean value.

pfl_rc_trace

PFL has a light-weight exception handling system using the pfl_rc_trace structure. It requires no heap allocations and no expensive system calls to unwind the stack, minimising the overhead of stack tracing. It has a simple and readable set of macros that abstract and encapsulate the implementation mechanism.

The pfl_rc_trace structure is initialised with a macro: PFL_RC_TRACE. A pointer to the structure is passed into any function that can generate an exception.

On return from the function, the exception state is checked with pfl_rc_trace_is_error() - this is the equivalent of "catching" the exception - how the exception is handled.

Once identified as an exception, the stack trace can be printed, logged or used to create a new PFL_Str with the following calls:-

  • pfl_rc_trace_print()

    Print to stdout.

  • pfl_rc_trace_print_to_log()

    Log on stderr.

  • pfl_rc_trace_to_str()

    Create a new PFL_Str object.

N.B. The pfl_rc_trace functions are generic macros which can accept either a pfl_rc_trace variable or a pointer to the variable e.g. pfl_rc_trace_is_error(val) works when val is either a pfl_rc_trace rc parameter or a pfl_rc_trace * rc_trace

Setting an exception

There are two ways to set the exception state:-

  1. pfl_rc_trace_log_err() - for exceptions which set errno.

  2. pfl_rc_trace_log_exception() - for exceptions which do not set errno.

Example - exception_demo1.c

Demonstrating the pfl_rc_trace_log_err() call to log an exception with an errno.

#include "PFL.h"

/**
 * Demo of pfl_rc_trace_log_err()
 */

double 
square_root (double parm, pfl_rc_trace * rc_trace)
{
    errno = 0;
    
    double result = sqrt(parm);
    
    if (errno)
    {
        // log an error - sets the error number
        pfl_rc_trace_log_err(rc_trace, PFL_RC_EXCEPTION);
        
        return 0; // return a dummy value
    }
    
    return result;
}

int 
main (int argc, char * argv[]) 
{
    pfl_env_init();
    
    // initialise the rc trace
    pfl_rc_trace rc = PFL_RC_TRACE;

    // sqrt(-1) will generate an errno.
    double result = square_root(-1, &rc);
    
    if (pfl_rc_trace_is_error(rc))  // "catch" the error
    {
        // an exception has been raised 
        pfl_rc_trace_print(rc);
    }
    else
    {
        printf("result = %f\n", result);
    }
        
    pfl_end();    
}

/* Output:-
--------------------------------------------------------

exception_demo1.c main 35 RC: Exception
 error: Numerical argument out of domain (33)
 - exception_demo1.c, fn: square_root, line: 13

--------------------------------------------------------
*/

Example - exception_demo2.c

Demonstrating the pfl_rc_trace_log_exception() call to log an exception without an errno.

#include "PFL.h"

/**
 * Demo of pfl_rc_trace_log_exception()
 */
 
float 
divide (float dividend, float divisor, pfl_rc_trace * rc_trace)
{
    if (divisor == 0)
    {
        // log an exception - no errno.
        pfl_rc_trace_log_exception(rc_trace, PFL_RC_EXCEPTION);
        
        return 0; // return a dummy value
    }
    
    return dividend / divisor;
}

int 
main (int argc, char * argv[]) 
{
    pfl_env_init();
    
    // initialise the rc trace
    pfl_rc_trace rc = PFL_RC_TRACE;

    float result = divide(3, 0, &rc);
    
    if (pfl_rc_trace_is_error(rc))  // "catch" the error
    {
        // an exception has been raised - print the stack trace
        pfl_rc_trace_print(rc);
    }
    else
    {
        printf("result = %f\n", result);
    }
         
    pfl_end();    
}

/* Output:-
--------------------------------------------------------

exception_demo2.c main 36 RC: Exception
 - exception_demo2.c, fn: divide, line: 13

--------------------------------------------------------
*/

Setting an info message

An additional free text message of up to 80 bytes may be set to provide specific information about the exception.

  1. pfl_rc_trace_set_info() - uses printf formatting to set the info message.

  2. pfl_rc_trace_set_msg() - copies the contents of a PFL_Str to the info message.

Example - exception_demo3.c

Demonstrating the pfl_rc_trace_set_info() call to set a free text message.

#include "PFL.h"

/**
 * Demo of pfl_rc_trace_set_info()
 */
 
float 
divide (float dividend, float divisor, pfl_rc_trace * rc_trace)
{
    if (divisor == 0)
    {
        // log an exception
        pfl_rc_trace_log_exception(rc_trace, PFL_RC_EXCEPTION);
        
        // set the free text info
        pfl_rc_trace_set_info(rc_trace, "dividend: %f, divisor: %f", dividend, divisor);
        
        return 0; // return a dummy value
    }
    
    return dividend / divisor;
}

int 
main (int argc, char * argv[]) 
{
    pfl_env_init();
    
    // initialise the rc trace
    pfl_rc_trace rc = PFL_RC_TRACE;

    float result = divide(3, 0, &rc); 
    
    if (pfl_rc_trace_is_error(rc))  // "catch" the error
    {
        // an exception has been raised - print the stack trace
        pfl_rc_trace_print(rc);
    }
    else
    {
        printf("result = %f\n", result);
    }

    pfl_end();    
}

/* Output:
--------------------------------------------------------

exception_demo3.c main 39 RC: Exception
 dividend: 3.000000, divisor: 0.000000
 - exception_demo3.c, fn: divide, line: 13

--------------------------------------------------------
*/

Throwing an exception

When handling an exception within an intermediate function, it is possible to throw the exception up to the higher level function for handling. This is done with pfl_rc_trace_throw() and works similarly to logging the exception but just adds an additional line to the stack trace.

As an alternative to throwing the exception, the intermediate function may log a different exception type with pfl_rc_trace_log_exception(). This has the same effect as throwing it (adding a line to the stack trace) but also overwrites the exception to the new type.

Example - exception_demo4.c

Demonstrating the pfl_rc_trace_throw() call to log a throw of the exception to the calling function.

#include "PFL.h"

/**
 * Demo of pfl_rc_trace_throw()
 */

float 
divide (float dividend, float divisor, pfl_rc_trace * rc_trace)
{
    if (divisor == 0)
    {
        // log an exception
        pfl_rc_trace_log_exception(rc_trace, PFL_RC_EXCEPTION);

        // set the free text info        
        pfl_rc_trace_set_info(rc_trace, "dividend: %f, divisor: %f", dividend, divisor);        
        
        return 0; // return a dummy value
    }
    
    return dividend / divisor;
}

float
divide_ints (int dividend, int divisor, pfl_rc_trace * rc_trace)
{
    float result = divide((float) dividend, (float) divisor, rc_trace);
    
    if (pfl_rc_trace_is_error(rc_trace)) // "catch" the error
    {
        // throw the exception - logging this function in the stacktrace.
        pfl_rc_trace_throw(rc_trace);
        
        return 0; // return a dummy value
    }    
    
    return result;
}

int 
main (int argc, char * argv[]) 
{
    pfl_env_init();
    
    // initialise the rc trace
    pfl_rc_trace rc = PFL_RC_TRACE;

    float result = divide_ints(3, 0, &rc);
    
    if (pfl_rc_trace_is_error(rc))  // "catch" the error
    {
        // an exception has been raised - print the stack trace
        pfl_rc_trace_print(rc);
    }
    else
    {
        printf("result = %f\n", result);
    }
        
    pfl_end();    
}

/* Output:-
--------------------------------------------------------

exception_demo4.c main 56 RC: Exception
 dividend: 3.000000, divisor: 0.000000
 - exception_demo4.c, fn: divide, line: 13
 - exception_demo4.c, fn: divide_ints, line: 33

--------------------------------------------------------
*/

Declaring new exceptions

Additional exceptions can be defined with the PFL_RC_DECLARE() macro. It takes the name of the new exception, its parent exception and its text description as parameters.

pfl_rc_trace provides an "is a" function macro pfl_rc_trace_exception_is_a() which works like an object "is a". i.e. an exception will return true if it is itself or its parent or its grandparent etc.

Example - exception_demo5.c

Demonstrating the PFL_RC_DECLARE() macro and pfl_rc_trace_exception_is_a() call to create a new exception type.

#include "PFL.h"

/**
 * Demo of PFL_RC_DECLARE()
 */
 
// declare MY_ARITHMETIC_EXC as child of PFL_RC_EXCEPTION
PFL_RC_DECLARE(MY_ARITHMETIC_EXC,  PFL_RC_EXCEPTION,  "Arithmetic exception");

// declare MY_DIV_BY_ZERO_EXC as child of MY_ARITHMETIC_EXC
PFL_RC_DECLARE(MY_DIV_BY_ZERO_EXC, MY_ARITHMETIC_EXC, "Divide by zero exception");

float 
divide (float dividend, float divisor, pfl_rc_trace * rc_trace)
{
    if (divisor == 0)
    {
        // log an exception
        pfl_rc_trace_log_exception(rc_trace, MY_DIV_BY_ZERO_EXC);

        // set the free text info        
        pfl_rc_trace_set_info(rc_trace, "dividend: %f, divisor: %f", dividend, divisor);        
        
        return 0; // return a dummy value
    }
    
    return dividend / divisor;
}

float
divide_ints (int dividend, int divisor, pfl_rc_trace * rc_trace)
{
    float result = divide((float) dividend, (float) divisor, rc_trace);
    
    if (pfl_rc_trace_is_error(rc_trace)) // "catch" the error
    {
        // throw the exception
        pfl_rc_trace_throw(rc_trace);
        
        return 0; // return a dummy value
    }    
    
    return result;
}

int 
main (int argc, char * argv[]) 
{
    pfl_env_init();
    
    // initialise the rc trace
    pfl_rc_trace rc = PFL_RC_TRACE;

    float result = divide_ints(3, 0, &rc);
    
    if (pfl_rc_trace_is_error(rc))  // "catch" the error
    {
        // an exception has been raised - print the stack trace
        pfl_rc_trace_print(rc);
    }
    else
    {
        printf("result = %f\n", result);
    }
    
    if (pfl_rc_trace_exception_is_a(rc, MY_DIV_BY_ZERO_EXC))
    {
        printf("rc is %s\n", MY_DIV_BY_ZERO_EXC.text);
    }
    
    if (pfl_rc_trace_exception_is_a(rc, MY_ARITHMETIC_EXC))
    {
        printf("rc is %s\n", MY_ARITHMETIC_EXC.text);
    }    

    if (pfl_rc_trace_exception_is_a(rc, PFL_RC_EXCEPTION))
    {
        printf("rc is %s\n", PFL_RC_EXCEPTION.text);
    }            
    
    assert(!pfl_rc_trace_exception_is_a(rc, PFL_RC_ERR));
        
    pfl_end();    
}

/* Output:-
--------------------------------------------------------

exception_demo5.c main 62 RC: Divide by zero exception
 dividend: 3.000000, divisor: 0.000000
 - exception_demo5.c, fn: divide, line: 19
 - exception_demo5.c, fn: divide_ints, line: 39

rc is Divide by zero exception
rc is Arithmetic exception
rc is Exception

--------------------------------------------------------
*/

Additional Notes

The overview and examples above provide a high-level introduction and cover the majority of cases. However, there are some more technical details which may be worth mentioning at least briefly, for completeness.

  • A pfl_rc_trace can be reset allowing re-use after handling an exception with pfl_rc_trace_clear().

  • Under the hood, the pfl_rc_trace rc = PFL_RC_TRACE; construct creates a literal PFL_RC_Ctx object on the stack rather than the heap. This removes the need for a malloc and means that it is not necessary to scope or free the object for the majority of situations - the stack memory will be reclaimed at the end of the function or block scope.

    However, it is possible to generate a heap allocated copy of the internal PFL_RC_Ctx if it is needed outside of the function scope. This can be done with pfl_rc_trace_get_new_ctx() which clones the internal ctx onto the heap.

  • The full set of pfl_rc_trace macro functions are:-

    • pfl_rc_trace_log_err(val, exc)

      Log an error with an errno value

    • pfl_rc_trace_log_exception(val, exc)

      Log an exception with no system errno value

    • pfl_rc_trace_throw(val)

      Throw the pfl_rc_trace up to the calling function

    • pfl_rc_trace_set_msg(val, msg)

      Set a free text message from a PFL_Str to add info to the exception

    • pfl_rc_trace_set_info(val, ...)

      Set an info text message using printf formatting_

    • pfl_rc_trace_print_to_log(val)

      Print to log

    • pfl_rc_trace_print(val)

      Print to stdout

    • pfl_rc_trace_clear(val)

      Clear a pfl_rc_trace

    • pfl_rc_trace_is_error(val)

      Check if an rc_trace is in error

    • pfl_rc_trace_exception_is_a(val, exc)

      Check if an rc_trace exception is of a type

    • pfl_rc_trace_get_new_ctx(val)

      Create a new duplicate PFL_RC_Ctx allocated on the heap

    • pfl_rc_trace_on_error_exit(val)

      Exit if an rc_trace is in error

    • pfl_rc_trace_to_str(val)

      Create a new PFL_Str from the trace