相关疑难解决方法(0)

如何按其运行时类型抛出异常?

我想调用一个可能抛出异常的函数。如果它确实抛出异常,我想捕获它并将异常对象传递给处理函数。处理程序函数的默认实现只是抛出异常。这是说明问题的精简代码:

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 …
Run Code Online (Sandbox Code Playgroud)

c++ exception-handling

5
推荐指数
1
解决办法
392
查看次数

将子类对象作为异常抛出

在读取异常时,我知道在抛出对象时,总是基于静态类型信息构造对象。如果发生异常,我们如何抛出子类对象?以下是《更有效的C ++》一书中的几行内容:

class Widget{...};

class SpecialWidget: public Widget {...};

void passAndThrowWidget()
{
    SpecialWidget localSpecialWidget;
    ...
    Widget& rw = localSpecialWidget;
    throw rw; // this throws an exception of type widget!
}
Run Code Online (Sandbox Code Playgroud)

即使rw指向,也会在此处引发Widget异常SpecialWidget。那是因为rw的静态类型是Widget,而不是Special-Widget。rw实际上是指S pecialWidget,您的编译器并不关心。他们只关心rw的静态类型。

这就解释了为什么会发生这种情况,但没有提供解决问题的方法。

c++ c++11

1
推荐指数
1
解决办法
76
查看次数

标签 统计

c++ ×2

c++11 ×1

exception-handling ×1