Exception handling syntax: Difference between revisions

Content deleted Content added
Line 217:
The most common way to implement exception handling in standard C
is to use [[setjmp/longjmp]] functions:
<source lang=c>
#include <setjmp.h>
#include <stdio.h>
enum { SOME_EXCEPTION = 1 };
jmp_buf state;
int main()
{
int exception;
if((exception = setjmp(state)) == 0) // try
{
if(/* something happened */)
longjmp(state, SOME_EXCEPTION); // throw SOME_EXCEPTION
}
else switch(exception)
{
case SOME_EXCEPTION: // catch SOME_EXCEPTION
puts("SOME_EXCEPTION caught");
break;
default: // catch ...
puts("Some strange exception");
}
return 0;
}
</source>
 
Some [[operating system]]s also have similar features, for example [[Microsoft Windows]] has "[[Structured Exception Handling]]" (SEH):
#include <setjmp.h>
<source lang=c>
#include <stdio.h>
int filterExpression (EXCEPTION_POINTERS* ep) {
enum { SOME_EXCEPTION = 1 };
++ep->ContextRecord->Eip;
jmp_buf state;
return EXCEPTION_CONTINUE_EXECUTION;
int main()
}
{
int main() {
int exception;
static int zero;
if((exception = setjmp(state)) == 0) // try
__try {
if(/* something happenedzero = *1/)zero;
printf ("Past the exception.\n");
longjmp(state, SOME_EXCEPTION); // throw SOME_EXCEPTION
} __except (filterExpression (GetExceptionInformation())) {
}
printf ("Handler called.\n");
else switch(exception)
{
case SOME_EXCEPTION: // catch SOME_EXCEPTION
puts("SOME_EXCEPTION caught");
break;
default: // catch ...
puts("Some strange exception");
}
return 0;
}
</source>
 
Some [[operating system]]s also have similar features, for example [[Microsoft Windows]] has "[[Structured Exception Handling]]" (SEH):
 
int filterExpression (EXCEPTION_POINTERS* ep) {
++ep->ContextRecord->Eip;
return EXCEPTION_CONTINUE_EXECUTION;
}
int main() {
static int zero;
__try {
zero = 1/zero;
printf ("Past the exception.\n");
} __except (filterExpression (GetExceptionInformation())) {
printf ("Handler called.\n");
}
return 0;
}
 
* see also [[Vectored Exception Handling]] (VEH).