为了在catch子句中处理异常,需要知道异常提供哪些接口。所有标准异常只提供一个可用的接口函数:what(),用以获取异常“型别之外的附加信息”。

namespace std {
  class exception {
  public:
    virtual const char* what() const throw();
    …
  };
}

what()返回的字符串,很大程度决定了帮助的级别和信息的详细度。该字符串是以null结尾的“multibyte”字符串,也可以轻松转换为wstring并显示出来。what()返回的C-string在其所属的异常对象销毁后,就不再有效(标准没有强制)。

除了what(),再没有任何异常提供任何其它成员函数,能够描述异常的种类。唯一通用的异常评估手段,大概只有打印一途。

try {
  …
}
catch (const std::exception& error) {
  // print implementation-defined error message
  std::cerr << error.what() << std::endl;
}

唯一可能实现的另一个异常评估手段是,根据异常的精确型别,自己得出推论。例如,如果抛出bad_alloc异常,可能是因为程序企图获得更多内存。

【学习资料】 《c++标准程序库》

相关文章:

  • 2021-12-11
  • 2022-12-23
  • 2021-07-02
  • 2022-01-08
  • 2022-12-23
  • 2021-07-04
  • 2021-07-27
猜你喜欢
  • 2021-08-10
  • 2022-01-29
  • 2022-12-23
  • 2022-12-23
  • 2021-11-16
  • 2021-11-09
  • 2021-10-25
相关资源
相似解决方案