Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling common parts of exceptions together

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?

like image 741
LiKao Avatar asked Apr 13 '12 11:04

LiKao


People also ask

How do you handle multiple exceptions?

By handling multiple exceptions, a program can respond to different exceptions without terminating it. In Python, try-except blocks can be used to catch and respond to one or multiple exceptions. In cases where a process raises more than one possible exception, they can all be handled using a single except clause.

How do I combine two exceptions in Java?

When catching multiple exceptions in a single catch block, the rule is generalized to specialized. This means that if there is a hierarchy of exceptions in the catch block, we can catch the base exception only instead of catching multiple specialized exceptions.


1 Answers

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.

like image 89
Matthieu M. Avatar answered Oct 01 '22 20:10

Matthieu M.