-
Notifications
You must be signed in to change notification settings - Fork 27
nutshell
Guillermo Calvo edited this page Feb 27, 2019
·
4 revisions
📝:
exceptions4c is an exception handling framework for C.
Because it's way more convenient to treat errors as exceptions, rather than checking the status of the last operation.
-
try
: when a block of code is aware of the possibility that some exception can be thrown within it. -
finally
: when a block of code needs to clean things up, regardless of any exception. -
throw
: when some part of the program finds an error that can't handle, or something really bad happens: division by zero, segmentation fault, etc... -
catch
: ...the flow of the program jumps to a block of code that is able to handle the error.
Cleaning up:
void * buffer = malloc(1024);
try{
int bar = foo(buffer);
}finally{
free(buffer);
}
Ensuring preconditions:
int stack_pop(Stack * stack){
if(stack->elements == 0){
throw(EmptyStackException);
}
stack->elements--;
/* ... */
}
Recovering from errors:
int * pointer = NULL;
try{
int oops = *pointer;
}catch(BadPointerException){
printf("No problem ;-)");
}
/* ... */
- Drop the
e4c.h
ande4c.c
in your project. #include "e4c.h"
- Create a
e4c_using_context
code block inmain
.
int main(int argc, char * argv[]){
e4c_using_context(E4C_TRUE){
try{
/* ... */
if(error) throw(MyException, "Some error happened.");
/* ... */
}catch(NullPointerException){
/* ... */
}finally{
/* ... */
}
}
}