A code throws out several types of exceptions, the handling of which is the same. For example:

try { // ... } catch (InvalidOperationException e) { // ... } catch (ArgumentException e) { // ... } 

The code executed in the catch blocks is identical. I put it in the onException () function. But, nevertheless, all the same, quite a lot of code branches.

Is there a way to make the filter on exceptions different - more briefly?

  • 3
    not? catch (Exception e) {// ...} - Specter

2 answers 2

Here is an example of solving a similar question on stackflowflow.

 catch (Exception ex) { if (ex is InvalidOperationException || ex is ArgumentException) { onException(); } else { throw; } } 
  • well, why throw? - Specter
  • 2
    So that further handlers could catch. - Jofsey 2:42 pm
  • All right, one confuses, brackets are not needed yet? (ex is InvalidOperationException || ex is ArgumentException) - AlexAndR
  • @Jofsey, the question of how to reduce the number of handlers, but no, you are throwing an exception further - Specter
  • one
    the question of not duplicating the code in each catch section, if I understood correctly. - AlexAndR
 try { // ... } catch (Exception e) { // ... } 

All types of extras are inherited from one, you can handle it. If you do not want to interfere with the exceptions you provided for from others, make a common ancestor for InvalidOperationException and ArgumentException and handle it (the latter only if it is your own exceptions).