哪个是正确的?捕获(_com_error e)还是捕获(_com_error&e)?

时间:2020-03-06 14:54:04  来源:igfitidea点击:

我应该使用哪一个?

catch (_com_error e)

或者

catch (_com_error& e)

解决方案

第二。这是我引用萨特的尝试

"按价值投掷,按参考捕捞"

Learn to catch properly: Throw exceptions by value (not pointer) and
  catch them by reference (usually to const). This is the combination
  that meshes best with exception semantics. When rethrowing the same
  exception, prefer just throw; to throw e;.

这是第73项的完整内容。按值抛出,按引用捕获。

避免按值捕获异常的原因是它隐式地制作了异常的副本。如果异常是子类的,则有关该异常的信息将丢失。

try { throw MyException ("error") } 
catch (Exception e) {
    /* Implies: Exception e (MyException ("error")) */
    /* e is an instance of Exception, but not MyException */
}

通过引用捕获通过不复制异常避免了此问题。

try { throw MyException ("error") } 
catch (Exception& e) {
    /* Implies: Exception &e = MyException ("error"); */
    /* e is an instance of MyException */
}

绝对是第二个。如果我们具有以下条件:

class my_exception : public exception
{
  int my_exception_data;
};

void foo()
{
  throw my_exception;
}

void bar()
{
  try
  {
    foo();
  }
  catch (exception e)
  {
    // e is "sliced off" - you lose the "my_exception-ness" of the exception object
  }
}

另外,请注意,使用MFC时,可能必须通过指针进行捕获。否则,@ JaredPar的答案就是我们通常应该使用的方式(希望永远不必处理抛出指针的事情)。

就个人而言,我会选择第三个选项:

catch (const _com_error& e)