问题描述
我是从Java转到C ++,所以请耐心等待。
在C ++中,有没有办法让我使用异常来捕获
分段错误(例如当我访问某个位置时
数组的结尾)?
谢谢。
Hi, I''m coming over from Java to C++, so please bear with me.
In C++, is there a way for me to use exceptions to catch
segmentation faults (e.g. when I access a location off
the end of an array)?
Thanks.
推荐答案
这是依赖于实现的;标准没有提到它。如果你试图通过捕获
Throwable找到等同于Java的运行时异常,那么你可以尝试这样的东西,但它'保证不会被捕获 - 因此你仍然会受到分段
故障或意外程序中止形式的总线错误。
尝试
{
//访问无效的内存位置。
} catch(...)
{
std :: cerr<<"发生了不好的事情\ nn"
}
------- ----------
catch(...) - 有点等同于catch(throwable),提防
实现细节并继续阅读关于
的编译器供应商条款。
Best,
It is implementation dependent; standard says nothing of it. If you''re
trying to find an equivalent to Java ''s run-time exception by catching
Throwable, then you can try something like this, but it''s NOT
guaranteed be caught - thus you can still suffer from segmentation
fault or bus error in form of unexpected program abort.
try
{
//access invalid memory location.
}catch(...)
{
std::cerr<<"something bad happened\n"
}
-----------------
catch(...) -- is somewhat equivalent to catch(throwable), beware the
implementation detail and read on compiler vendor provisions regarding
it.
Best,
如果使用向量而不是数组并使用at()成员函数而不是
比下标运算符,超出范围
访问时抛出异常。但是,对于
分段错误,没有通用的C ++异常机制。
Windows有结构化异常。除了C ++异常。这些
结构化异常确实包括分段错误(或访问违规,因为它们通常被称为b $ b)。其他平台可能有类似的设施,但我不知道它们。
-
John Carson
If you use vectors instead of arrays and use the at() member function rather
than the subscript operator, an exception is thrown for out of range
accesses. There is, however, no general C++ exception mechanism for
segmentation faults.
Windows has "structured exceptions" in addition to C++ exceptions. These
structured exceptions do include segmentation faults (or "access violations"
as they are more commonly called). Other platforms may have similar
facilities, but I don''t know about them.
--
John Carson
这篇关于使用异常来捕获分段错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!