【问题标题】:What is the difference between catch(...) vs catch(CException *)?catch(...) 与 catch(CException *) 有什么区别?
【发布时间】:2011-09-14 06:33:42
【问题描述】:

CException 是 VC++ 抛出的所有异常的基类型,所以它应该捕获所有异常,对吧?

【问题讨论】:

标签: c++ visual-c++ exception-handling


【解决方案1】:

C++ 异常可以是任何类型。使用 catch() 可以指定要捕获的异常类型作为参数。 (...) 的特殊情况是您将捕获任何其他未在之前的捕获中指定的异常。

标准库的 C++ 异常基础是 std::exception。要捕获所有异常,C++ 程序中的标准方法如下:

(例如在 main 函数中)

try
{

}
catch( const std::exception & e )
{
// catch standard exceptions, you can use e.what() to know what exception you caught
}
catch( ... )
{
// catch all other types but you can't do much with them
}

即使有可能,也不建议抛出您自己的不继承自 std::exception 的异常。但 CException 似乎没有继承自它。

在您的情况下,我建议您执行以下操作以捕获所有可能出现的异常(再次,例如在您的主函数和主线程函数中):

try
{
}
catch( const CException & e )
{
// catch all CExceptions
//as far as I know it is ok now to catch CException by reference with modern Microsoft compilers? It was not always the recommended microsoft way
}
catch( const std::exception & e )
{
// catch standard C++ exception
}
catch( ... )
{
// catch others
}

与往常一样,如果不习惯,可能很难知道什么是标准 C++ 和什么是 Windows API。

【讨论】:

    【解决方案2】:

    CException 不是所有扩展的基本类型(它可能是 MFC 代码使用的所有异常的基本类型,但仅此而已)。

    在 C++ 中,你可以抛出 anything;它不必是“异常”子类,甚至不必是对象。例如写throw 42;throw new std::vector<string>() 是完全合法的;

    那么区别就很明显了:catch(CException) 只会捕获 CException 及其子类的抛出实例,而另一个会捕获任何东西。

    【讨论】:

    • 我不确定通过新分配的指针抛出(不要这样做)和按值捕获(也不要这样做)是否明智。你可以在 c++ 中抛出任何东西,但也不建议这样做。
    • @Nikko:恕我直言 throw/catch “最佳实践”超出了问题的范围。
    • 为什么不呢?我认为我们应该提供展示最佳实践的示例。
    • @Nikko:问题是理论上的
    • 请注意,catch(CException) 可能不会捕获任何 MFC 异常,因为 MFC 会抛出 CException* 异常。你必须使用catch(CException*)
    【解决方案3】:
    throw "ex";
    

    实际上会抛出一个字符串(嗯,const char*,但你知道我的意思)。

    catch (TYPE t)
    

    只会捕获 TYPE 类型的对象(不一定是异常)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-29
      • 2013-06-09
      • 2019-03-10
      • 1970-01-01
      • 2012-11-20
      • 2017-09-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多