关于捕获异常的良好实践 [英] About catching exception good practices

查看:166
本文介绍了关于捕获异常的良好实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C ++ 11中写了一个小程序,并且第一次使用异常。



我有一个问题,有效地捕获异常,并且在一些谷歌搜索后,我仍然没有答案。



这里是问题:
什么是更高效)在捕获异常之前(const?)lvalue引用,或者通过(const?)rvalue引用?



在代码中,这给出:



1)

  try {throw std :: exception {what}; } 
catch(std :: exception& ex){}

2)

  try {throw std :: exception {what}; } 
catch(const std :: exception& ex){}



  try {throw std :: exception {what}; } 
catch(std :: exception&& ex){}

4) / p>

  try {throw std :: exception {what}; } 
catch(const std :: exception&& ex){}


方案

您应该通过const lvalue引用(2)捕获:

  try {throw std :: exception {什么}; } 
catch(const std :: exception& ex){}

p>

在C ++ 11中,(通过使用 shared_future )两个线程可以解开相同的异常同一时间。即使您不知道使用 shared_future ,除非您控制整个应用程序,否则您的代码中可能会发生这种情况。



如果两个线程被捕获,同时释放相同的异常,并且一个或两个线程修改异常,那么你有一个竞争条件。



只要你不必在catch子句中修改异常对象,让编译器为你执行该策略 - catch通过 const& 。如果你确实需要修改异常,那么请复制它,修改副本并抛出副本。如果你确定这不会切断你的异常对象(通常情况下,如果你捕获 std :: exception ),你可以通过捕捉值来做到这一点。


I'm writing a little program in C++11 and really use exceptions for one of the first time.

I've got a question about how to catch the exceptions efficiently, and after some googling I still don't have the answer.

Here is the question : What is the more efficient (or recommended) between catching the exception by (const?) lvalue reference, or by (const?) rvalue reference?

In code this give :

1)

try { throw std::exception{"what"}; }
catch (std::exception& ex) {}

2)

try { throw std::exception{"what"}; }
catch (const std::exception& ex) {}

3)

try { throw std::exception{"what"}; }
catch (std::exception&& ex) {}

4)

try { throw std::exception{"what"}; }
catch (const std::exception&& ex) {}

解决方案

You should catch by const lvalue reference (2):

try { throw std::exception{"what"}; }
catch (const std::exception& ex) {}

Rationale:

In C++11 it is possible (via use of shared_future) that two threads could be unwinding the same exception at the same time. This can happen in your code even if you are not aware of shared_future being used, unless you control the entire application.

If two threads are caught unwinding the same exception simultaneously, and one or both of the threads modifies the exception, then you've got a race condition.

So as long as you don't have to modify the exception object in the catch clause, let the compiler enforce that policy for you - catch by const&. If you really do need to modify the exception, then make a copy of it, modify the copy and throw the copy. You can do this by catching by value if you are sure this won't slice your exception object (which is not usually the case if you are catching std::exception).

这篇关于关于捕获异常的良好实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆