本文介绍了C ++:“引发新的BadConversion(“ xxx”)”与“和“ 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]通过新建,您将必须 catch 一个指针。在这种情况下,该语言没有指定负责分配的人员,因此您必须建立自己的约定(通常是使捕获程序负责)。如果没有新,则需要通过引用捕获。

[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]如果您使用的是通常会抛出指针的框架,那么您可能希望效仿。否则,扔而没有新。另请参见。

[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”)”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-18 14:09