Handling common parts of exceptions together

前端 未结 3 556
心在旅途
心在旅途 2021-01-18 19: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

相关标签:
3条回答
  • 2021-01-18 20:30

    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;
    }
    
    0 讨论(0)
  • 2021-01-18 20:38

    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?

    0 讨论(0)
  • 2021-01-18 20:48

    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.

    0 讨论(0)
提交回复
热议问题