[英]How to throw a C++ exception
我对异常处理的理解很差(即,如何为自己的目的自定义 throw、try、catch 语句)。
例如,我定义了一个函数如下: int compare(int a, int b){...}
我希望该函数在 a 或 b 为负时抛出带有某些消息的异常。
我应该如何在函数的定义中解决这个问题?
简单的:
#include <stdexcept>
int compare( int a, int b ) {
if ( a < 0 || b < 0 ) {
throw std::invalid_argument( "received negative value" );
}
}
标准库附带了一个很好的内置异常对象集合,您可以抛出这些异常对象。 请记住,您应该始终按值抛出并按引用捕获:
try {
compare( -1, 3 );
}
catch( const std::invalid_argument& e ) {
// do stuff with exception...
}
您可以在每次尝试后使用多个 catch() 语句,因此您可以根据需要分别处理不同的异常类型。
您还可以重新抛出异常:
catch( const std::invalid_argument& e ) {
// do something
// let someone higher up the call stack handle it if they want
throw;
}
无论类型如何,都可以捕获异常:
catch( ... ) { };
虽然这个问题已经很老了并且已经得到了回答,但我只想添加一个关于如何在 C++11 中进行正确异常处理的注释:
std::nested_exception
和std::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"
只需在需要的地方添加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) {
// ...
}
}
另外,看看Boost.Exception 。
您可以定义在发生特定错误时抛出的消息:
throw std::invalid_argument( "received negative value" );
或者你可以这样定义它:
std::runtime_error greatScott("Great Scott!");
double getEnergySync(int year) {
if (year == 1955 || year == 1885) throw greatScott;
return 1.21e9;
}
通常,你会有一个try ... catch
块,如下所示:
try {
// do something that causes an exception
}catch (std::exception& e){ std::cerr << "exception: " << e.what() << std::endl; }
添加到此答案中,因为此时为此问答创建另一个答案似乎并不有利。
在您创建自己的自定义异常的情况下,该异常派生自std::exception
,当您捕获“所有可能的”异常类型时,您应该始终以可能catch
的“派生最多的”异常类型开始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;
}
笔记:
正确的顺序应该是反之亦然,即 - 首先你catch (const MyException& e)
然后是catch (const std::exception& e)
。
如您所见,当您按原样运行程序时,将执行第一个 catch 子句(这可能是您一开始并不想要的)。
即使在第一个 catch 子句中捕获的类型是std::exception
类型,也会调用what()
的“正确”版本 - 因为它是通过引用捕获的(至少将捕获的参数std::exception
类型更改为按价值计算 - 您将在操作中体验“对象切片”现象)。
如果“由于抛出 XXX 异常这一事实而产生的某些代码......”对异常类型做了重要的事情,那么这里的代码存在不当行为。
如果捕获的对象是“普通”对象,例如: class Base{};
和class Derived : public Base {}
...
Ubuntu 18.04.1 上的g++ 7.3.0
会产生一个警告,指出上述问题:
在函数 'voidIllustrationDerivedExceptionCatch()': item12Linux.cpp:48:2: 警告: 'MyException' 类型的异常将被捕获 catch(const MyException& e) ^~~~~
item12Linux.cpp:43:2: 警告:由较早的处理程序用于 'std::exception' catch (const exception& e) ^~~~~
再次,我会说,这个答案只是添加到这里描述的其他答案(我认为这一点值得一提,但无法在评论中描述)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.