一起处理异常的共同部分 [英] Handling common parts of exceptions together

查看:66
本文介绍了一起处理异常的共同部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有一些要重构的代码。大量异常具有用于所有异常的一些通用代码,以及一些需要针对每种特定异常类型分别处理的特定代码。我试图弄清楚如何摆脱每个 catch 块中的共同部分。一个想法是这样做:

I currently have some code I am trying to refactor. A large set of exceptions has some common code for all exceptions as well as some specific code which needs to be handled separately for each specific exception type. I am trying to figure out how to get rid of the common part in each catch block. One Idea is to do it like this:

try {
  /* Stuff that may fail */
} catch( const std::exception & ) {
  /* do common part here */
  try { throw; } 
  catch( const exception1 & ) {
    /* do stuff for exception1 here */
  }
  catch( const exception2 & ) {
    /* do stuff for exception2 here */
  }
}

是否有更好的方法可以排除这种共同的逻辑,或者实际上有理由完全避免这种尝试吗?

Is there a better way to factor out this common logic, or is there actually a reason to avoid this attempt altogether?

推荐答案

通常,尝试 / 捕获仅稀疏地出现在代码中。问题是,例如,在提早返回的情况下,很多时候也应该执行 catch 子句中的操作。

In general, try/catch should only appear sparsely in the code. The problem is that many times the actions done in a catch clause should also be done in case of early return, for example.

Idiomatic C ++广泛使用RAII来避免需要在 catch 子句中进行清理的情况,该子句通常会删除大部分工作。

Idiomatic C++ uses RAII extensively to avoid situation where you need to cleanup in a catch clause, which generally removes most of the work.

现在,您的模式本身还不错, ,它确实考虑了常见问题。

Now, your pattern is not so bad per se, it does factor the common stuff. But this common stuff could perhaps be handled automatically.

在我偶然发现的所有代码库中,只有几次我真正看到了<$ c $的用法。 c> catch 子句,请勿将其用作离合器。

In all the code bases I have stumbled upon, only a few times did I see a genuine use of catch clause, don't use it as a clutch.

这篇关于一起处理异常的共同部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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