【问题标题】:c++ exception naked throw [duplicate]c ++异常裸抛出[重复]
【发布时间】:2012-08-26 18:58:51
【问题描述】:

可能重复:
What is the difference between throw and throw with arg of caught exception?
Does catch (…) work on throw; with no object?

这会崩溃:

try
{
    if(1)
        throw;
}
catch(...)
{
    printf("hi");
}

我以为我能做到,但我想不行。在不需要任何信息的情况下,正确的投掷方式是什么?

【问题讨论】:

    标签: c++ windows visual-c++ exception try-catch


    【解决方案1】:

    “裸抛出”重新抛出已被捕获的异常。如果没有东西可以重新抛出,效果就不好了。

    你真的可以扔任何东西,比如throw "Error!";,即使那不是太有用。否则你可以试试

    if (x == 1)
        throw std::runtime_error("x == 1 is not a good value here")`.
    

    【讨论】:

    • 我不会使用 throw 信息。有没有一些标准做法,比如throw std::defaultthrow?
    • 你应该使用例外。 catch(...) 基本上毫无价值,因为您不知道如何从“任何”异常中恢复。但是,如果您坚持使用完全通用的异常类型,则可以选择像 throw false; 这样的简单类型,或者使用标准的 std::runtime_error()。
    【解决方案2】:
    #include <exception>
    
    try
    {
        if(1)
            throw std::exception();
    }
    catch(...)
    {
        printf("hi");
    }
    

    这可能会更好,这取决于你在做什么:

    class my_exception : public std::exception {};
    

    那么,

    try
    {
        if(1)
            throw my_exception();
    }
    catch(my_exception)
    {
        printf("hi");
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-22
      • 1970-01-01
      • 1970-01-01
      • 2013-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多