今天我在想另一种语言中存在的try/catch块.谷歌搜索了一会儿,但没有结果.据我所知,C中没有try/catch这样的东西.然而,有没有一种方法可以"模拟"它们
今天我在想另一种语言中存在的try/catch块.谷歌搜索了一会儿,但没有结果.据我所知,C中没有try/catch这样的东西.然而,有没有一种方法可以"模拟"它们
C本身不支持异常,但你可以用setjmp
和longjmp
次调用来模拟它们.
static jmp_buf s_jumpBuffer;
void Example() {
if (setjmp(s_jumpBuffer)) {
// The longjmp was executed and returned control here
printf("Exception happened here\n");
} else {
// Normal code execution starts here
Test();
}
}
void Test() {
// Rough equivalent of `throw`
longjmp(s_jumpBuffer, 42);
}
这个网站有一个很好的教程,介绍如何模拟setjmp
和longjmp
的异常