std :: uncaught_exceptions对于避免所有异常都有用吗?

时间:2017-01-18 05:07:16

标签: c++ c++11

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

1 个答案:

答案 0 :(得分:1)

  

我可以使用std::uncaught_exceptions来实现这个目标吗?

考虑以下代码:

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

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

  

我需要在我的应用程序中捕获分段错误和其他未知异常。但我不知道我怎么能这样做!

C ++中的异常处理可以通过try-catch块完成,您可以使用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 WikiMIT也有一些处理和调试段错误的提示。

希望可以提供帮助。

相关问题