Exceptions in C

This is a small page for my hack in plain C (not C++) --- Implementing Exceptions in C Programming language, written by Adomas Paltanavičius.

What I have to show is the tarballs and source. There is also outdated low-level documentation (PDF, 80KB). It was written few years ago as a school project, and might be inaccurate etc.

Newest version is 0.1.5 released on April 10th, 2005.

Brief introduction

This hack implements fully-functional nested exceptions with these constructs:

Also, it allows to define various datatypes for exception object (default is int, can be anything from char * to struct foo *).


This idea came from I do not know where, yet it resulted into quite interesting hack.

Example program

The example program demonstrates nearly all capabilities of this hack. It consists of two files: a header containing customizations to the core, and main source file.

/* This is example program for EXCC.

#include <stdio.h>

#include "exception-local.h"

exception_t exception_make(exception_type_t type, int param1) {
  exception_t ex;

  ex.type = type;
  ex.param1 = param1;
  return ex;

int divide(int a, int b) {
  if (b == 0) {
    throw (DIVISION_BY_ZERO, a);
  } else {
    return a/b;

int main(int argc, char **argv) {
  int a, b, result;

  if (argc < 3) {
    printf("Usage: %s A B\n", argv[0]);
    return 1;
  } else {
    try {
      a = atoi(argv[1]);
      b = atoi(argv[2]);
      result = divide(a, b);
      printf("%d/%d=%d\n", a, b, result);
    } except {
      on (DIVISION_BY_ZERO) {
        printf("Caught up division by zero (%d/0).\n",
    printf("Program is going to end its short life.\n");
    return 0;
typedef enum { DIVISION_BY_ZERO } exception_type_t;

typedef struct {
  exception_type_t type;
  int param1;
} exception_t;

#define __EXC_TYPE                exception_t
#define __EXC_MAKE(type, param1)  exception_make(type, param1)
#define __EXC_ON(type)            exception_make(type, 0)
#define __EXC_EQ(a, b)            ((a).type == (b).type)
#define __EXC_PRINT(e, stream)    fprintf(stream, "%d:%d", e.type, e.param1)
#define EXCEPTION                 __exc_code

#undef __EXC_DEBUG

#include "exception.h"

Compiling and running

Pretty straight forward.

admp@sols:~/excc/example$ gcc exception.c -c
admp@sols:~/excc/example$ gcc exception.o example.c -o example
admp@sols:~/excc/example$ ./example
Usage: ./example A B
admp@sols:~/excc/example$ ./example 100 2
Program is going to end its short life.
admp@sols:~/excc/example$ ./example 100 0
Caught up division by zero (100/0).
Program is going to end its short life.



Write if you have any questions, suggestions or bug reports. Any other comments regarding this hack are also welcome!

Return to the homepage.