主前后的异常处理 [英] Exception handling before and after main

查看:129
本文介绍了主前后的异常处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这些情况下可以处理异常:

Is it possible to handle exceptions in these scenarios:


  1. 在输入main()之前从构造函数抛出

  2. 离开main()之后抛出析构函数


推荐答案


    <
  1. 不,你应该从不允许异常抛出一个析构函数。
  2. 你可以用一个try-catch来包装你的构造函数。 >
  1. You can wrap up your constructor withing a try-catch inside of it.
  2. No, you should never allow exception throwing in a destructor.

如何在构造函数中嵌入try-catch的有趣的不太常见的特性:

The funny less-known feature of how to embed try-catch in a constructor:

object::object( int param )
try
  : optional( initialization )
{
   // ...
}
catch(...)
{
   // ...
}

是的,这个有效的C ++。这里的附加好处是,try将捕获由类的数据成员的构造函数抛出的异常,即使它们没有在ctor初始化器中提及或没有ctor初始化器:

Yes, this is valid C++. The added benefit here is the fact that the try will catch exceptions thrown by the constructors of the data members of the class, even if they're not mentioned in the ctor initializer or there is no ctor initializer:

struct Throws {
  int answer;
  Throws() : answer(((throw std::runtime_error("whoosh!")), 42)) {}
};

struct Contains {
  Throws baseball;
  Contains() try {} catch (std::exception& e) { std::cerr << e.what() << '\n'; }
};

这篇关于主前后的异常处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆