通过引用捕获std :: exception? [英] catching std::exception by reference?

查看:134
本文介绍了通过引用捕获std :: exception?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个愚蠢的问题。我阅读了关于std :: exception的这篇文章 http://www.cplusplus.com/doc/tutorial/exceptions/

I have a silly question. I read this article about std::exception http://www.cplusplus.com/doc/tutorial/exceptions/

catch(例外& e),它说:


我们放置了一个处理程序,通过引用捕获异常对象(注意和符号和类型之后),因此这也捕获了从异常派生的类,像类的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.

这是否意味着使用&你也可以捕获父类的异常?我想&是在std :: exception中预定义的,因为最好将e(std :: exception)作为引用传递给对象。

Does this mean that by using "&" you can also catch exception of the parent class? I thought & is predefined in std::exception because it's better to pass e (std::exception) as reference than object.

推荐答案

使用& 的原因与例外并不是避免切片。如果你不使用& ,C ++会尝试将抛出的异常复制到新创建的 std :: exception ,可能会丢失该过程中的信息。示例:

The reason for using & with exceptions is not so much polymorphism as avoiding slicing. If you were to not use &, C++ would attempt to copy the thrown exception into a newly created std::exception, potentially losing information in the process. Example:

#include <stdexcept>
#include <iostream>

class my_exception : public std::exception {
  virtual const char *what() const throw() {
    return "Hello, world!";
  }
};

int main() {
  try {
    throw my_exception();
  } catch (std::exception e) {
    std::cout << e.what() << std::endl;
  }
  return 0;
}

这将打印 std ::异常(在我的例子中, St9exception )而不是 Hello,world!原始异常对象通过切片丢失。如果我们改变为&

This will print the default message for std::exception (in my case, St9exception) rather than Hello, world!, because the original exception object was lost by slicing. If we change that to an &:

#include <stdexcept>
#include <iostream>

class my_exception : public std::exception {
  virtual const char *what() const throw() {
    return "Hello, world!";
  }
};

int main() {
  try {
    throw my_exception();
  } catch (std::exception &e) {
    std::cout << e.what() << std::endl;
  }
  return 0;
}



现在我们看到 Hello,world! code>。

Now we do see Hello, world!.

这篇关于通过引用捕获std :: exception?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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