C ++:抛出异常,使用'new'或不? [英] C++: Throwing exceptions, use 'new' or not?
问题描述
抛出新的FoobarException(Baz参数);
或抛出FoobarException(Baz参数);
? 抓到时,我总是使用 catch(FoobarException& e)
以防万一,但我从来没有找到一个坚实的答案是否我不得不使用新的或不在C ++(Java绝对),或者它只是程序员的偏好。
所以这是正确的方法:
try
{
throw FoobarException(argument);
}
catch(const FoobarException& ex)
{
cout<< ex.what()<< ENDL;
}
不要抛出使用new创建的异常,因为谁负责删除它没有明确定义。此外,在错误处理期间执行分配可能会引发另一个异常,从而掩盖原始问题。
您不必通过const引用(非const将正常工作) ),但我喜欢这样做。然而,你应该总是通过引用(而不是值)来捕获异常。如果没有,可以将异常类型切片。
Is it proper to use throw new FoobarException(Baz argument);
or throw FoobarException(Baz argument);
?
When catching I always use catch(FoobarException& e)
"just in case" but I never could find a solid answer whether I had to use new or not in C++ (Java definitely) or if it was just a preference of the programmer.
Exceptions in C++ should be thrown by value, and caught by reference.
So this is the proper way:
try
{
throw FoobarException(argument);
}
catch( const FoobarException &ex )
{
cout << ex.what() << endl;
}
Don't throw an exception created with new, since who's responsible for deleting it is not well-defined. In addition, performing allocations during error handling can throw another exception, obscuring the original problem.
You don't have to catch by const reference (non-const will work fine), but I like doing it anyway. You should however always by reference (not by value) to catch the exception polymorphically. If you don't, the exception's type could be sliced.
这篇关于C ++:抛出异常,使用'new'或不?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!