C++: Throwing exceptions, use 'new' or not?

萝らか妹 提交于 2019-12-18 10:50:16

问题


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.


回答1:


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.




回答2:


unless there is some special requirement not to, I always throw by value and catch by const reference. This is because the new itself could throw an exception as well, during error handling, it is best to avoid things which can cause exceptions.



来源:https://stackoverflow.com/questions/6801796/c-throwing-exceptions-use-new-or-not

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!