Handling common parts of exceptions together

跟風遠走 提交于 2020-01-21 11:47:47

问题


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 */
  }
}

However this strikes me as somewhat ugly.

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


回答1:


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++ 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.

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.




回答2:


A large set of exceptions has some common code

Move the common code into a function or method. Call the method from each catch. Just like eliminating any other duplication; the presence of a try..catch makes no difference.

But if you are really concerned about "a large set of exceptions", the real problem might be that you have a large set of exceptions. Why do different exceptions require different handling at all? Are exceptions really being used for only exceptional events?




回答3:


I would really just move the common code to a function.

Here is another idea:

try {
  /* Stuff that may fail */
} catch( const std::exception & e) {
  /* do common part here */  
  if (const exception1 * e1 = dynamic_cast<const exception1*>(&e) {
    /* do stuff for exception1 here */
  } else if (const exception2 * e2 = dynamic_cast<const exception2*>(&e) {
    /* do stuff for exception2 here */
  } else
    throw;
}


来源:https://stackoverflow.com/questions/10140383/handling-common-parts-of-exceptions-together

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