A simple exception handling library for C that provides try-catch functionality with error handling and throwing capabilities.
curl -o try.h https://raw.githubusercontent.com/DilemaFixer/TryC/main/try.h
curl -o try.c https://raw.githubusercontent.com/DilemaFixer/TryC/main/try.cTryC implements a simple exception handling mechanism for C programs, allowing structured error handling similar to languages with native try-catch support.
// Error structure to hold exception information
typedef struct error {
const char *message; // Error message
const char *file_name; // File where error occurred
size_t code; // Error code
size_t line; // Line number where error occurred
size_t offset; // Column offset where error occurred
} error;// Creates a new error object with provided information
error *new_error(const char *message, const size_t code, const char* file_name, size_t line, size_t offset);
// Frees memory allocated for an error object
void free_error(error *e);
// Throws an error, triggering jump to the nearest catch block
void trow_error(error *e);
// Gets the current thrown error
error *get_error();// Begin a try block
#define try
// Begin a catch block to handle exceptions
#define catch
// End a try-catch block
#define tryend
// Throw an exception with a message and code
#define trow(message, code)
// Throw an exception with a message, code, and offset
#define trow_with_offset(message, code, offset)
// Re-throw an error to upper level
#define error_go_top(error)
// Get error code from current error
#define get_code(code_var)
// Log the current error to stderr
#define log_error()
// Macro to implement main function with error handling
#define IMPLEMENT_ERROR_HANDLING_MAIN()#include "try.h"
int divide(int a, int b) {
if (b == 0) {
trow("Division by zero", 101);
}
return a / b;
}
int main() {
try
int result = divide(10, 0);
printf("Result: %d\n", result);
catch
error* e = get_error();
printf("Caught error: %s (code: %zu) at %s:%zu\n",
e->message, e->code, e->file_name, e->line);
free_error(e);
tryend
return 0;
}Required headers: try.h
You can also configure your application to catch all unhandled exceptions at the top level by defining USE_ERROR_HANDLING before including the header. This will automatically rename your main function to application_main and implement a wrapper main that handles errors:
#define USE_ERROR_HANDLING
#include "try.h"
// When USE_ERROR_HANDLING is defined, write main as application_main
// The actual main function will be generated by IMPLEMENT_ERROR_HANDLING_MAIN
int application_main(int argc, char** argv) {
// Your code here
trow("Some error occurred", 500);
return 0;
}
// This generates the actual main function with error handling
IMPLEMENT_ERROR_HANDLING_MAIN()Required headers: try.h