C++:抛出异常,使用“new”;或不?

发布于 2024-11-26 12:18:42 字数 224 浏览 4 评论 0原文

使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

彼岸花ソ最美的依靠 2024-12-03 12:18:43

除非有特殊要求,否则我总是按值抛出并按 const 引用捕获。这是因为 new 本身也可能引发异常,在错误处理期间,最好避免可能导致异常的事情。

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.

妞丶爷亲个 2024-12-03 12:18:42

C++ 中的异常应该按值抛出,并按引用捕获。

所以这是正确的方法:

try
{
    throw FoobarException(argument);
}
catch( const FoobarException &ex )
{
    cout << ex.what() << endl;
}

不要抛出用 new 创建的异常,因为谁负责删除它并没有明确定义。此外,在错误处理期间执行分配可能会引发另一个异常,从而掩盖了原始问题。

您不必通过 const 引用来捕获(非 const 也可以正常工作),但无论如何我喜欢这样做。然而,您应该始终通过引用(而不是通过值)来多态地捕获异常。如果不这样做,异常的类型可能会被分割。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文