C ++获取在catch(...)块中捕获的异常的描述 [英] C++ get description of an exception caught in catch(...) block

查看:971
本文介绍了C ++获取在catch(...)块中捕获的异常的描述的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以得到

catch(...)

.what()的std :: exception。

block? something like .what() of std::exception.

推荐答案

能够使用:

catch(...) {
    handle_exception();
}

void handle_exception() {
    try {
        throw;
    } catch (const std::exception &e) {
        std::cout << e.what() << "\n";
    } catch (const int i) {
        std::cout << i << "\n";
    } catch (const long l) {
        std::cout << l << "\n";
    } catch (const char *p) {
        std::cout << p << "\n";
    } catch (...) {
        std::cout << "nope, sorry, I really have no clue what that is\n";
    }

等等,对于你认为可能抛出的许多不同类型。如果你真的不知道什么可能抛出,那么即使是第二个到最后一个是错误的,因为有人可能会抛出一个 char * ,没有指向一个nul - 终止字符串。

and so on, for as many different types as you think might be thrown. If you really know nothing about what might be thrown then even that second-to-last one is wrong, because somebody might throw a char* that doesn't point to a nul-terminated string.

通常不是一个坏主意,抛出任何不是 std :: exception 派生类。原因 std :: exception exists是允许每个人抛出和捕捉他们可以做一些有用的对象。在一个玩具程序中,你只是想从那里出来,甚至不能打扰包括一个标准的头,OK,可能会抛出一个 int 或一个字符串文字。我不认为我会做一个正式接口的那部分。您抛出的任何异常都是您的正式接口的一部分,即使您以某种方式忘记记录它们。

It's generally a bad idea to throw anything that isn't a std::exception or derived class. The reason std::exception exists is to allow everybody to throw and catch objects that they can do something useful with. In a toy program where you just want to get out of there and can't even be bothered to include a standard header, OK, maybe throw an int or a string literal. I don't think I'd make that part of a formal interface. Any exceptions you throw are part of your formal interface, even if you somehow forgot to document them.

这篇关于C ++获取在catch(...)块中捕获的异常的描述的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆