Re-throw an exception inside catch block

隐身守侯 提交于 2019-12-10 13:19:43

问题


Can anyone please confirm me if this information is correct or not:

In C++, inside catch block we can re-throw an exception using throw statement, but the thrown exception should have the same type as the current caught one.


回答1:


The rethrown exception can have a different type. This compiles and runs correctly on VS2012

// exceptions
#include <iostream>
using namespace std;

int main () {
try{
      try
      {
        throw 20;
      }
      catch (int e)
      {
        cout << "An exception occurred. Exception Nr. " << e << '\n';
        throw string("abc");
      }
    }
    catch (string ex)
    {
        cout<<"Rethrow different type (string): "<< ex<<endl;
    }
  return 0;
}

Output:

An exception occurred. Exception Nr. 20

Rethrow different type (string): abc




回答2:


throw; all by itself in a catch block re-throws the exception that was just caught. This is useful if you need to (e.g.) perform some cleanup operation in response to an exception, but still allow it to propagate upstack to a place where it can be handled more fully:

catch(...)
{
   cleanup();
   throw;
}

But you are also perfectly free to do this:

catch(SomeException e)
{
   cleanup();
   throw SomeOtherException();
}

and in fact it's often convenient to do exactly that in order to translate exceptions thrown by code you call into into whatever types you document that you throw.




回答3:


Not necessarily. As soon as you catch it, it is up to you what to do with it. You can either throw an exception that is the same or a completely new exception. Or, not do anything at all.



来源:https://stackoverflow.com/questions/23437927/re-throw-an-exception-inside-catch-block

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!