Open Ir1Ka opened 3 years ago
暂无法实现 finally 语句块。 要实现 finally 语句可以,应该需要重新定义 return 关键字或使用替换宏。
$ uname -srvmpio
Linux 5.10.4-1-default #1 SMP Wed Dec 30 13:10:15 UTC 2020 (4169c1f) aarch64 aarch64 aarch64 GNU/Linux
$ gcc --version
gcc (SUSE Linux) 10.2.1 20201202 [revision e563687cf9d3d1278f45aaebd03e0f66531076c9]
Copyright (C) 2020 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
$ cat /etc/os-release
NAME="openSUSE Tumbleweed"
# VERSION="20210108"
ID="opensuse-tumbleweed"
ID_LIKE="opensuse suse"
VERSION_ID="20210108"
PRETTY_NAME="openSUSE Tumbleweed"
ANSI_COLOR="0;32"
CPE_NAME="cpe:/o:opensuse:tumbleweed:20210108"
BUG_REPORT_URL="https://bugs.opensuse.org"
HOME_URL="https://www.opensuse.org/"
DOCUMENTATION_URL="https://en.opensuse.org/Portal:Tumbleweed"
LOGO="distributor-logo"
$ make DEBUG=1
gcc -Werror -Wall -g -Iinclude -fPIC -DCTRY_DEBUG -c -o main.o main.c
gcc -Werror -Wall -g -Iinclude -fPIC -DCTRY_DEBUG -c -o ctry-catch.o ctry-catch.c
gcc -shared -L. -o libctry-catch.so ctry-catch.o
gcc -L. -o ctry-catch \
main.o -lctry-catch
$ LD_LIBRARY_PATH=`pwd`:${LIBRARY_PATH} ./ctry-catch 3 1
exception0 3 exception1 1
[0] try
[1] try
[2] try
throw 3
[2] catch 3
[2] throw 1
[1] catch 1
$ echo $?
1
$ LD_LIBRARY_PATH=`pwd`:${LIBRARY_PATH} ./ctry-catch 3 2
exception0 3 exception1 2
[0] try
[1] try
[2] try
throw 3
[2] catch 3
[2] throw 2
main.c test_try_catch().L39: [1] Unknown exception 2, throwing ...
main.c main().L78: [0] Unknown exception 2, exiting ...
$ echo $?
2
$ LD_LIBRARY_PATH=`pwd`:${LIBRARY_PATH} ./ctry-catch 5
exception0 5 exception1 0
[0] try
[1] try
[2] try
throw 5
main.c test_try_catch().L34: [2] Unknown exception 5, throwing ...
main.c test_try_catch().L39: [1] Unknown exception 5, throwing ...
main.c main().L78: [0] Unknown exception 5, exiting ...
$ echo $?
5
$ LD_LIBRARY_PATH=`pwd`:${LIBRARY_PATH} ./ctry-catch
exception0 0 exception1 0
[0] try
[1] try
[2] try
exit normal
$ echo $?
0
在 C 语言中实现 try-catch
C 语言中提供了
setjmp
和longjmp
来实现跨函数无条件跳转。include/ctry-catch.h
ctry-catch.c
main.c
Makefile