如何抛出C++异常

Ter*_* Li 226 c++ exception-handling

我对异常处理的理解很差(即,如何根据自己的目的自定义throw,try,catch语句).

例如,我已经定义了一个函数如下: int compare(int a, int b){...}

当a或b为负时,我希望函数抛出一些带有异常消息的异常.

我应该如何在函数的定义中处理这个问题?

nsa*_*ers 323

简单:

#include <stdexcept>

int compare( int a, int b ) {
    if ( a < 0 || b < 0 ) {
        throw std::invalid_argument( "received negative value" );
    }
}
Run Code Online (Sandbox Code Playgroud)

标准库附带了一系列可以抛出的内置异常对象.请记住,您应该始终按值引用并通过引用捕获:

try {
    compare( -1, 3 );
}
catch( const std::invalid_argument& e ) {
    // do stuff with exception... 
}
Run Code Online (Sandbox Code Playgroud)

每次尝试后都可以有多个catch()语句,因此如果需要,可以单独处理不同的异常类型.

您还可以重新抛出异常:

catch( const std::invalid_argument& e ) {
    // do something

    // let someone higher up the call stack handle it if they want
    throw;
}
Run Code Online (Sandbox Code Playgroud)

并且无论类型如何都要捕获异常:

catch( ... ) { };
Run Code Online (Sandbox Code Playgroud)

  • 你通常会用一个简单的`throw;`重新抛出(重新抛出原始对象并保留它的类型)而不是`throw e;`(抛出被捕对象的副本,可能改变它的类型). (24认同)
  • 而且你应该总是捕获异常作为const (21认同)
  • @TerryLiYifeng如果自定义例外更有意义,那就去吧。您可能仍想从std :: exception派生并保持接口相同。 (2认同)
  • 再次+1了,但我认为const非常重要-因为它凸显了它现在是临时对象这一事实-因此修改是无用的。 (2认同)
  • @AdrianCornish:虽然这不是暂时的.非const捕获[可能有用](http://www.boost.org/doc/libs/1_48_0/libs/exception/doc/tutorial_transporting_data.html). (2认同)

Cat*_*lus 17

只需添加throw需要的地方,并try阻止处理错误的调用者.按照惯例,你应该只抛出派生的东西std::exception,所以<stdexcept>先包括.

int compare(int a, int b) {
    if (a < 0 || b < 0) {
        throw std::invalid_argument("a or b negative");
    }
}

void foo() {
    try {
        compare(-1, 0);
    } catch (const std::invalid_argument& e) {
        // ...
    }
}
Run Code Online (Sandbox Code Playgroud)

另外,请查看Boost.Exception.


GPM*_*ler 13

虽然这个问题相当陈旧并且已经得到了解答,但我只想补充说明如何在C++ 11中进行适当的异常处理:

使用std::nested_exceptionstd::throw_with_nested

它在StackOverflow 这里这里描述了如何通过简单地编写一个适当的异常处理程序来重新抛出嵌套异常,如何在代码内部获得异常回溯,而无需调试器或繁琐的日志记录.

由于您可以对任何派生的异常类执行此操作,因此可以向此类回溯添加大量信息!您也可以在GitHub上查看我的MWE,其中回溯看起来像这样:

Library API: Exception caught in function 'api_function'
Backtrace:
~/Git/mwe-cpp-exception/src/detail/Library.cpp:17 : library_function failed
~/Git/mwe-cpp-exception/src/detail/Library.cpp:13 : could not open file "nonexistent.txt"
Run Code Online (Sandbox Code Playgroud)


ser*_*rup 7

您可以定义在发生特定错误时要抛出的消息:

throw std::invalid_argument( "received negative value" );
Run Code Online (Sandbox Code Playgroud)

或者你可以像这样定义它:

std::runtime_error greatScott("Great Scott!");          
double getEnergySync(int year) {                        
    if (year == 1955 || year == 1885) throw greatScott; 
    return 1.21e9;                                      
}                                                       
Run Code Online (Sandbox Code Playgroud)

通常,你会有一个try ... catch像这样的块:

try {
// do something that causes an exception
}catch (std::exception& e){ std::cerr << "exception: " << e.what() << std::endl; }
Run Code Online (Sandbox Code Playgroud)


Guy*_*ham 5

想要在自定义例外的情况下,将此处所述的其他答案添加到其他注释中。

在创建自己的自定义异常(源自)的情况下std::exception,当您捕获“所有可能的”异常类型时,应始终catch以可能捕获的“最派生”异常类型开始子句。请参阅示例(执行的操作):

#include <iostream>
#include <string>

using namespace std;

class MyException : public exception
{
public:
    MyException(const string& msg) : m_msg(msg)
    {
        cout << "MyException::MyException - set m_msg to:" << m_msg << endl;
    }

   ~MyException()
   {
        cout << "MyException::~MyException" << endl;
   }

   virtual const char* what() const throw () 
   {
        cout << "MyException - what" << endl;
        return m_msg.c_str();
   }

   const string m_msg;
};

void throwDerivedException()
{
    cout << "throwDerivedException - thrown a derived exception" << endl;
    string execptionMessage("MyException thrown");
    throw (MyException(execptionMessage));
}

void illustrateDerivedExceptionCatch()
{
    cout << "illustrateDerivedExceptionsCatch - start" << endl;
    try 
    {
        throwDerivedException();
    }
    catch (const exception& e)
    {
        cout << "illustrateDerivedExceptionsCatch - caught an std::exception, e.what:" << e.what() << endl;
        // some additional code due to the fact that std::exception was thrown...
    }
    catch(const MyException& e)
    {
        cout << "illustrateDerivedExceptionsCatch - caught an MyException, e.what::" << e.what() << endl;
        // some additional code due to the fact that MyException was thrown...
    }

    cout << "illustrateDerivedExceptionsCatch - end" << endl;
}

int main(int argc, char** argv)
{
    cout << "main - start" << endl;
    illustrateDerivedExceptionCatch();
    cout << "main - end" << endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

注意:

0)正确的顺序应该相反,即,首先是您catch (const MyException& e),然后是catch (const std::exception& e)

1)如您所见,当按原样运行程序时,将执行第一个catch子句(这可能是您最初希望的内容)。

2)即使在第一个catch子句中捕获的类型是type std::exceptionwhat()也将调用的“适当”版本-因为它是通过引用捕获的(至少将catch的参数std::exception类型更改为按值捕获-您将体验到活动中的“对象切片”现象。

3)如果“由于抛出XXX异常而导致某些代码...”对异常类型具有重要的意义,则这里的代码行为不当。

4)如果捕获的对象是“正常”对象,例如:class Base{};class Derived : public Base {}...,这也很重要。

5)g++ 7.3.0在Ubuntu 18.04.1上产生警告,指出上述问题:

在函数'voidillustratedDerivedExceptionCatch()'中:item12Linux.cpp:48:2:警告:类型为'MyException'的异常将被捕获​​catch(const MyException&e)^ ~~~~

item12Linux.cpp:43:2:警告: 较早的处理程序针对'std :: exception'catch (const exception&e)^ ~~~~

同样,我会说,这个答案只有到ADD到这里所描述的其他答案(我认为这一点值得一提,但在注释不能描绘它)。