抛出C ++异常时抛出什么? [英] What to throw when throwing C++ exceptions?
问题描述
这可能是一个愚蠢的问题,但是在C ++中,当我想抛出一个异常时,我会抛出什么?
This might be kind of a silly question, but in C++, when I want to throw an exception.. what do I throw?
我应该抛出std :: exception,还是由标准库保留?还是应该抛出一个字符串或int?或者我应该抛出任何我觉得是适当的?
Am I supposed to throw std::exception, or is that reserved by the standard library? Or should I throw a string or int? Or should I just throw whatever I feel is appropriate?
推荐答案
抛出一个派生自 std的类: :例外
;如果你 #include< stdexcept>
,你可以从一些现成的,有用的派生类。
Throw a class that's derived from std::exception
; if you #include <stdexcept>
, you can pick from a number of ready-made, useful derived classes.
从 std :: exception
允许您的处理程序遵循可识别的样式,因为您可以随时使用 .what()
获取文本消息。不要抛出原始类型,因为它们不携带语义信息。
Deriving from std::exception
allows your handlers to follow a recognizable style, as you can always use .what()
to get a textual message. Don't throw primitive types, since they carry no semantic information.
这篇关于抛出C ++异常时抛出什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!