尝试用C catch语句 [英] Try catch statements in C
问题描述
我今天想着try / catch块在其他语言中存在。用Google搜索了一会儿这一点,但没有结果。据我所知,没有这样的事情在C.然而try / catch语句,是有办法模拟呢?结果
当然,也有断言和其他技巧,但没有像try / catch语句,也赶上引发的异常。谢谢
I was thinking today about the try/catch blocks existent in another languages. Googled for a while this but with no result. From what I know, there is not such a thing as try/catch in C. However, is there a way to "simulate" them?
Sure, there is assert and other tricks but nothing like try/catch, that also catch the raised exception. Thank you
推荐答案
C本身并不支持例外,但你可以模仿他们在一定程度上与的setjmp
和的longjmp
来电。
C itself doesn't support exceptions but you can simulate them to a degree with setjmp
and longjmp
calls.
static jmp_buf s_jumpBuffer;
void Example() {
if (setjmp(s_jumpBuffer)) {
// The longjmp was executed and returned control here
printf("Exception happened\n");
} else {
// Normal code execution starts here
Test();
}
}
void Test() {
// Rough equivalent of `throw`
longjump(s_jumpBuffer, 42);
}
本网站有关于如何模拟与的setjmp
例外一个很好的教程和的longjmp
This website has a nice tutorial on how to simulate exceptions with setjmp
and longjmp
这篇关于尝试用C catch语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!