q09*_*987 9 c++ exception-handling exception
// 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();
}
Run Code Online (Sandbox Code Playgroud)
[Q1]当我们在函数中抛出异常时,抛出新的ClassName()和抛出ClassName()之间有什么区别?
[Q2]哪个更好?
谢谢
[A1]有了throw new,你需要catch一个指针.在这种情况下,语言没有指定谁负责解除分配,所以你必须建立自己的约定(通常你会让捕手负责).没有new,你会想catch参考.
[A2]如果你在一个通常会抛出指针的框架中,你可能想要效仿.否则,throw没有new.另请参阅C++ FAQ,第17.14项.
| 归档时间: |
|
| 查看次数: |
1756 次 |
| 最近记录: |