C++:抛出异常,使用“new”;或不?
使用 throw new FoobarException(Baz argument); 或 throw FoobarException(Baz argument); 是否正确?
在捕获时,我总是使用 catch(FoobarException& e)
“以防万一”,但我永远找不到一个可靠的答案,无论我是否必须在 C++ 中使用 new (绝对是 Java),或者它只是程序员的偏好。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
除非有特殊要求,否则我总是按值抛出并按
const
引用捕获。这是因为new
本身也可能引发异常,在错误处理期间,最好避免可能导致异常的事情。unless there is some special requirement not to, I always throw by value and catch by
const
reference. This is because thenew
itself could throw an exception as well, during error handling, it is best to avoid things which can cause exceptions.C++ 中的异常应该按值抛出,并按引用捕获。
所以这是正确的方法:
不要抛出用 new 创建的异常,因为谁负责删除它并没有明确定义。此外,在错误处理期间执行分配可能会引发另一个异常,从而掩盖了原始问题。
您不必通过 const 引用来捕获(非 const 也可以正常工作),但无论如何我喜欢这样做。然而,您应该始终通过引用(而不是通过值)来多态地捕获异常。如果不这样做,异常的类型可能会被分割。
Exceptions in C++ should be thrown by value, and caught by reference.
So this is the proper way:
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.