如何通过其运行时类型抛出异常? [英] How to throw an exception by its run-time type?

查看:292
本文介绍了如何通过其运行时类型抛出异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想调用一个可能抛出异常的函数。如果它确实抛出异常,我想抓住它,并将异常对象传递给处理函数。处理函数的默认实现就是抛出异常。下面是用于说明问题的细节代码:

I want to call a function that may throw an exception. If it does throw an exception, I want to catch it and pass the exception object to a handler function. The default implementation of the handler function is simply to throw the exception. Here is whittled-down code to illustrate the issue:

struct base_exception : exception {
  char const* what() const throw() { return "base_exception"; }
};

struct derived_exception : base_exception {
  char const* what() const throw() { return "derived_exception"; }
};

void exception_handler( base_exception const &e ) {
  throw e; // always throws a base_exception object even if e is a derived_exception
}

int main() {
  try {
    throw derived_exception();
  }
  catch ( base_exception const &e ) {
    try {
      cout << e.what() << endl; // prints "derived_exception" as expected
      exception_handler( e );
    }
    catch ( base_exception const &e ) {
      cout << e.what() << endl; // prints "base_exception" due to object slicing
    }
  }
}


$ b b

但是,在 exception_handler()中的 throw e 会抛出异常的静态类型的副本,即 base_exception 。如何使 exception_handler()抛出具有正确的运行时类型 derived_exception 实际 $ c>?

However, the throw e in exception_handler() throws a copy of the static type of the exception, i.e., base_exception. How can I make exception_handler() throw the actual exception having the correct run-time type of derived_exception? Or how can I redesign things to get what I want?

推荐答案

您可以将 throw_me virtual函数在基本异常类中,并且让每个派生类重载它。派生类可以抛出正确的最导出类型,而不切片。即使该函数在每个类中具有相同的定义,它们也不一样 - 的类型在每种情况下都不同。

You can put a throw_me virtual function in the base exception class, and have every derived class override it. The derived classes can throw the proper most derived type, without slicing. Even though the function has the same definition in each class, they're not the same - the type of *this is different in each case.

struct base_exception : exception
{
  char const* what() const throw() { return "base_exception"; }
  virtual void throw_me() const { throw *this; }
};

struct derived_exception : base_exception
{
  char const* what() const throw() { return "derived_exception"; }
  virtual void throw_me() const { throw *this; }
};

void exception_handler( base_exception const &e ) {
  e.throw_me();
} 

这篇关于如何通过其运行时类型抛出异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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