Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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] When we throw an exception in the function, what is the difference between throw new ClassName() and throw ClassName()?

[Q2] Which one is better?

Thank you

like image 607
q0987 Avatar asked Feb 03 '23 23:02

q0987


2 Answers

[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] 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.

like image 179
Fred Foo Avatar answered Feb 05 '23 16:02

Fred Foo


throw new ClassName() throws pointer to ClassName. You need to catch (ClassName * pc). It's not good idea. If new returns null or throws then you have null pointer when you catch or you have double exception.

throw ClassName() is usual way to throw an exception. You need to catch (const ClassName & pc).

like image 23
Alexey Malistov Avatar answered Feb 05 '23 16:02

Alexey Malistov