通过引用捕获异常 [英] Catching exceptions by reference
问题描述
在此C ++教程中,在标准例外一节中,有一个示例代码使用从STL中的标准异常类派生的类:
In this C++ tutorial, in the section titled "Standard exceptions", there is this example code which uses a class derived from the standard exception class in the STL:
// standard exceptions
#include <iostream>
#include <exception>
using namespace std;
class myexception: public exception
{
virtual const char* what() const throw()
{
return "My exception happened";
}
} myex; //Declares an instance of myexception outside of the main function
int main () {
try
{
throw myex;
}
catch (exception& e) //My question is regarding this line of code
{
cout << e.what() << endl;
}
return 0;
}
代码打印出来 c $ c>。但是,如果我删除&符号,它会输出
std :: exception
,这是当你调用 what()$ c $
That code prints out My exception happened
. However, if I remove the ampersand, it prints out std::exception
, which is what happens when you call what()
with the standard exception class, not the derived class.
网站给出了这个解释:
我们放置了一个处理程序,通过引用
捕获异常对象(注意&之后的类型),因此这也捕获了从异常派生的
类,像myex对象类
myexception。
We have placed a handler that catches exception objects by reference (notice the ampersand & after the type), therefore this catches also classes derived from exception, like our myex object of class myexception.
抛出 myex
调用 catch
函数,并将 myex
作为参数传递。因为在这种情况下,我想象无论你是否通过值或引用抛出异常(这是和号做的正确吗?),因为你仍然抛出一个 myexception
而不是异常
。由于动态绑定和多态性等, e.what()
应该仍然打印出我的异常发生
而不是 std :: exception
。
Is throwing myex
kind of like "calling a the catch
function, and passing myex
as a parameter"? Because it that case, I would imagine that it doesn't matter whether you throw the exception by value or by reference (that's what the ampersand does right?), because you are still throwing a myexception
rather than an exception
. And due to dynamic binding and polymorphism or something like that, e.what()
should still print out My exception happened
rather than std::exception
.
推荐答案
对象切片。
如果你将一个派生类的对象赋给一个基类的一个实例(就像使用拷贝c'tor传递值一样) )所有派生类的信息将丢失(切片)。
If you assign an object of a derived class to an instance of a base class (as in the case of using a copy c'tor when passing by value) all the information of the derived class will be lost (sliced).
例如,
class Base {
int baseInfo;
};
class Derived : public Base
{
int someInfo;
};
然后,如果你这样写:
Derived myDerivedInstance;
Base baseInstance = myDerivedInstance;
然后, myDerivedInstance
中的someInfo在 baseInstance
中切片。
Then the "someInfo" in myDerivedInstance
is sliced away in baseInstance
.
这篇关于通过引用捕获异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!