簡體   English   中英

C ++捕獲基本異常,引發子級

[英]C++ catch base exception, throw child

我有以下例外。

class BaseException  : public Exception     {};
class ChildException : public BaseException {};
class FooException   : public BaseException {};

int throw_it() {
  try {
    throw ChildException();
  } catch(BaseException& exc) {
    throw exc;
  }
}

我有什么辦法可以使throw_it()catch子句拋出ChildException即使我正在捕獲BaseException

出於這個問題的目的,假設throw_it()可能拋出ChildExceptionFooException並且我不知道在編譯時哪個。

編輯

這可能是我的問題的更完整示例。

class BaseException : public Exception {};
class AException    : public Exception {};
class BException    : public Exception {};
class CException    : public Exception {};
class DException    : public Exception {};
class EException    : public Exception {};
class FException    : public Exception {};
class GException    : public Exception {};

void throw_it() {
  try {
    // Code
  } catch(AException exc) {
    log(exc);
    throw(exc);
  } catch(BException exc) {
    log(exc);
    throw(exc);
  } catch(CException exc) {
    log(exc);
    throw(exc);
  } catch(DException exc) {
    log(exc);
    throw(exc);
  } catch(EException exc) {
    log(exc);
    throw(exc);
  } catch(FException exc) {
    log(exc);
    throw(exc);
  } catch(GException exc) {
    log(exc);
    throw(exc);
  }
}

我試圖這樣寫:

void throw_it() {
  try {
    // Code
  } catch(BaseException exc) {
    log(exc);
    throw(exc);
  }
}
catch(BaseException& exc) {
  throw; // thows excact expeption
}

搜索“投擲”; http://www.cplusplus.com/doc/tutorial/exceptions/

投射是一種實現方法。 但是我認為那是個壞主意。

真正的問題是,您為什么要這樣做?

如果要拋出異常而不管其類型如何,只需將其重新拋出為:

catch(BaseException const & e)
{
     log(e);
     throw; //it rethrows the exception irrespective of its type!
}

那應該工作。 魔術發生在throw -因為異常被抓參考 ,它會拋出派生類型的例外,也就是說,如果該異常是ChildException ,然后throw將拋出ChildException ,不BaseException ,即使抓提到BaseException


如果要拋出特定的異常(而不是所有異常),請首先按特定的類型捕獲它:

//first write a lambda to avoid duplication of code!
auto handle_exception = [&](BaseException const & e) 
{
    //your duplicate code
};

try { /*....*/ }
catch(ChildException const & e)  //catch it by specific type
{
     handle_exception(e); //invoke the lambda to handle exception!
     //any additional (non-duplicate) code can go here or above it!

     throw; //it rethrows the exception!
}
catch(BaseException const & e) //the more general case
{
     handle_exception(e); //invoke the lambda to handle the exception
     //any additional (non-duplicate) code can go here or above it!
}

希望能有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM