Bri*_*ndy 66
在C中没有例外.在C中,错误由函数的返回值,进程的退出值,向进程发出的信号(程序错误信号(GNU libc))或CPU硬件中断(或其他通知错误)通知如果有,则形成CPU)(处理器如何处理除零的情况).
但是,在C++和其他语言中定义的异常.C++中的异常处理在C++标准"S.15异常处理"中指定,C标准中没有等效的部分.
vav*_*ava 31
在C中,您可以使用setjmp()和中longjmp()定义的函数的组合setjmp.h.维基百科的例子
#include <stdio.h>
#include <setjmp.h>
static jmp_buf buf;
void second(void) {
printf("second\n"); // prints
longjmp(buf,1); // jumps back to where setjmp
// was called - making setjmp now return 1
}
void first(void) {
second();
printf("first\n"); // does not print
}
int main() {
if ( ! setjmp(buf) ) {
first(); // when executed, setjmp returns 0
} else { // when longjmp jumps back, setjmp returns 1
printf("main"); // prints
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
注意:我实际上建议你不要使用它们,因为它们使用C++工作很糟糕(本地对象的析构函数不会被调用),而且很难理解发生了什么.而是返回某种错误.
Luc*_*nes 19
普通的旧C实际上并不支持异常.
您可以使用其他错误处理策略,例如:
FALSE并使用last_error变量或函数.见http://en.wikibooks.org/wiki/C_Programming/Error_handling.
小智 19
C中没有内置的异常机制; 你需要模拟异常及其语义.这通常是依靠setjmp和实现的longjmp.
周围有很多库,我正在实施另一个库.它被称为exceptions4c ; 它是便携式和免费的.您可以查看它,并将其与其他替代方案进行比较,以了解哪种方式最适合您.
C能够抛出C++异常,无论如何它们都是机器代码.例如,在bar.c中
// begin bar.c
#include <stdlib.h>
#include <stdint.h>
extern void *__cxa_allocate_exception(size_t thrown_size);
extern void __cxa_throw (void *thrown_exception, void* *tinfo, void (*dest) (void *) );
extern void * _ZTIl; // typeinfo of long
int bar1()
{
int64_t * p = (int64_t*)__cxa_allocate_exception(8);
*p = 1976;
__cxa_throw(p,&_ZTIl,0);
return 10;
}
// end bar.c
Run Code Online (Sandbox Code Playgroud)
在a.cc,
#include <stdint.h>
#include <cstdio>
extern "C" int bar1();
void foo()
{
try{
bar1();
}catch(int64_t x){
printf("good %ld",x);
}
}
int main(int argc, char *argv[])
{
foo();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
编译它
gcc -o bar.o -c bar.c && g++ a.cc bar.o && ./a.out
Run Code Online (Sandbox Code Playgroud)
产量
good 1976
Run Code Online (Sandbox Code Playgroud)
http://mentorembedded.github.io/cxx-abi/abi-eh.html有更多详细信息__cxa_throw.
我不确定它是否可移植,我在Linux上使用'gcc-4.8.2'进行测试.
这个问题是超级老的,但我偶然发现它并认为我会分享一种技术:除以零,或取消引用空指针.
问题只是"如何抛出",而不是如何捕获,甚至如何抛出特定类型的异常.我有一个很久以前的情况,我们需要触发C中的异常才能被C++捕获.具体来说,我们偶尔会报告"纯虚函数调用"错误,需要说服C运行时的_purecall函数抛出一些东西.所以我们添加了自己的_purecall函数除以零,并且繁荣,我们得到了一个我们可以捕获C++的异常,甚至使用一些堆栈乐趣来查看出错的地方.
| 归档时间: |
|
| 查看次数: |
104787 次 |
| 最近记录: |