// 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
[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.
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)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With