c++ - std::uncaught_exceptions 对避免所有异常有用吗?

标签 c++ c++11

<分区>

我需要在我的应用程序中捕获段错误和其他未知异常。但我不知道我该怎么做! 我可以为此目的使用 std::uncaught_exceptions 吗?

最佳答案

Can I use std::uncaught_exceptions for this aim?

考虑这段代码:

int main(int argc, char* argv[])
{
    int *val = NULL;
    *val = 1;
    std::cout << "uncaught: " << std::uncaught_exceptions() << std::endl;
    return 0;
}

这可能会导致段错误,并且不会输出任何内容。

I need to catch segmentation fault and other unknown exceptions in my application. But I do not know how I can do that!

C++ 中的异常处理可以通过 try-catch 完成 block ,你可以使用 std::signal函数来捕获某些错误,如 SIGSEGV, SIGFPE, or SIGILL , 例子:

#include <iostream>
#include <exception>
#include <csignal>
#include <cstdio>

extern "C" {
    void sig_fn(int sig)
    {
        printf("signal: %d\n", sig);
        std::exit(-1);
    }
}

int main(int argc, char* argv[])
{
    int *val = NULL;
    std::signal(SIGSEGV, sig_fn);
    try {
        *val = 1;
    } catch (...) {
        std::cout << "..." << std::endl;
    }
    if (std::uncaught_exception()) {
        std::cout << "uncaught" << std::endl;
    }
    std::cout << "return" << std::endl;
    return 0;
}

但是你要注意,这种异常处理实际上是为了清理和关闭,不一定是捕获和释放;以这段代码为例:

#include <iostream>
#include <exception>
#include <csignal>
#include <cstdio>

extern "C" {
    void sig_fn(int sig)
    {
        printf("signal: %d\n", sig);
    }
}

int main(int argc, char* argv[])
{
    int *val = NULL;
    std::signal(SIGSEGV, sig_fn);
    while (true) {
        try {
            *val = 1;
        } catch (...) {
            std::cout << "..." << std::endl;
        }
    }
    if (std::uncaught_exception()) {
        std::cout << "uncaught" << std::endl;
    }
    std::cout << "return" << std::endl;
    return 0;
}

此代码将永远导致并捕获段错误!

如果您试图捕获段错误,则需要首先调查段错误(或与此相关的任何错误)发生的原因并纠正该问题;以上面的代码为例:

int *val = NULL;
if (val == NULL) {
    std::cout << "Handle the null!" << std::endl;
} else {
    *val = 1;
}

进一步阅读:here is a SO Q&A关于段错误是什么,here is the Wiki在上面,和MIT还有一些关于处理和调试段错误的技巧。

希望对您有所帮助。

关于c++ - std::uncaught_exceptions 对避免所有异常有用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41711742/

相关文章:

c++ - 使用 GCC 编译 boost::multi_index 和 std::shared_ptr

c++ - 指向类成员的指针作为模板参数

c++ - 如何仅在派生类具有特定功能时才启用功能?

c++ - Cmake 中的 Boost 文件系统版本错误

C++11:一种新语言?

c++ - 具有不同所有者的 std::enable_shared_from_this

c++ - 快速读取带有 float 的文本文件

c++ - 从 'int' 到 'const char*' 的无效转换

c++ - 额外的静态数组破坏了 omapl138 目标 (ccs5.2) 上的 DSP 应用程序

c++ - C++11 中的 hash_value 函数