C ++:“引发新的BadConversion(“ xxx”)”与“和“ throw BadConversion(“ xxx”)” [英] C++ -- Difference between "throw new BadConversion("xxx")" and "throw BadConversion("xxx")"
问题描述
// http://www.parashift.com/c++-faq-lite/misc-technical-issues.html
class BadConversion : public std::runtime_error {
public:
BadConversion(std::string const& s)
: std::runtime_error(s)
{ }
};
inline std::string stringify(double x)
{
std::ostringstream o;
if (!(o << x))
throw BadConversion("stringify(double)");
// throw new BadConversion("stringify(double)");
return o.str();
}
[Q1]当我们在函数中抛出异常时,有什么区别
[Q1] When we throw an exception in the function, what is the difference between throw new ClassName() and throw ClassName()?
[Q2]哪个更好?
谢谢
推荐答案
[A1]通过新建
,您将必须新
,则需要通过引用捕获
。
[A1] With throw new
, you'll have to catch
a pointer. The language doesn't specify in this case who is responsible for deallocation, so you'll have to establish your own convention (typically you'd make the catcher responsible). Without new
, you'll want to catch
by reference.
[A2]如果您使用的是通常会抛出指针的框架,那么您可能希望效仿。否则,扔
而没有新
。另请参见 C ++常见问题解答,项目17.14 。
[A2] If you're in a framework that commonly throws pointers, you may want to follow suit. Else, throw
without new
. See also the C++ FAQ, item 17.14.
这篇关于C ++:“引发新的BadConversion(“ xxx”)”与“和“ throw BadConversion(“ xxx”)”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!