c++中try和catch的用法
时间: 2023-10-28 20:05:22 浏览: 23
在 C 语言中并没有 try 和 catch 这两个关键字,它们是 C++ 引入的异常处理机制的特殊语法。C 语言中可以通过一些技巧来实现类似的异常处理功能,比如使用 setjmp 和 longjmp 函数。
setjmp 函数用于设置一个跳转点,并返回一个整数值。longjmp 函数则用于跳转到之前设置的跳转点,从而实现异常处理的功能。
示例代码:
```c
#include <stdio.h>
#include <setjmp.h>
jmp_buf buf;
void foo(int x) {
if (x < 0) {
printf("Error: x is negative!\n");
longjmp(buf, 1);
}
printf("x = %d\n", x);
}
int main() {
if (setjmp(buf)) {
printf("Caught an exception!\n");
return 1;
}
foo(10);
foo(-1);
return 0;
}
```
在上面的代码中,foo 函数会检查传入的参数是否为负数,如果是,则会通过 longjmp 跳转回到之前设置的跳转点 buf,从而实现异常处理的功能。
当 foo 函数调用时,如果传入的参数为 10,则会输出 x = 10;如果传入的参数为 -1,则会输出 Error: x is negative! 并跳转到 setjmp 函数处,输出 Caught an exception!。