gpt4 book ai didi

c - 在 C 中尝试 catch 语句

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:51:08 25 4
gpt4 key购买 nike

我今天在想其他语言中存在的 try/catch block 。用谷歌搜索了一段时间,但没有结果。据我所知,C中没有try/catch这样的东西。但是,有没有办法“模拟”它们?
当然,有 assert 和其他技巧,但没有像 try/catch 那样也能捕获引发的异常。谢谢

最佳答案

C 本身不支持异常,但您可以使用 setjmplongjmp 调用在一定程度上模拟它们。

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);
}

这个网站有一个很好的教程,介绍如何使用 setjmplongjmp 模拟异常

关于c - 在 C 中尝试 catch 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22832793/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com