C++ try finally
时间: 2023-09-04 15:15:35 浏览: 50
The "try-finally" statement in C does not exist. C does not have a built-in exception handling mechanism like some other programming languages. However, it is possible to mimic the behavior of try-finally using a combination of setjmp() and longjmp() functions.
The setjmp() function sets a marker in the code that can be returned to later using longjmp(). By using these functions together, it is possible to implement a try-finally-like behavior.
Here's an example:
```
#include <setjmp.h>
#include <stdio.h>
jmp_buf buf;
void foo() {
printf("Entering foo()\n");
longjmp(buf, 1);
printf("Exiting foo()\n");
}
int main() {
if (setjmp(buf) == 0) {
printf("Before calling foo()\n");
foo();
} else {
printf("After calling foo()\n");
}
printf("Exiting main()\n");
return 0;
}
```
In this example, the setjmp() function sets a marker before calling foo(). When foo() is called, it immediately jumps back to the setjmp() call using longjmp(). The code after the setjmp() call is skipped, and the program continues from the point where setjmp() was called.
The output of this program is:
```
Before calling foo()
Entering foo()
After calling foo()
Exiting main()
```
As you can see, the code after the setjmp() call is executed after foo() is called, but before foo() has a chance to complete. This mimics the behavior of a try-finally statement, where the code in the finally block is executed regardless of whether an exception was thrown.