4

Is it good practice to append a general exception catch when handling exceptions. an example may make this question clearer

try{
 // do something
}catch(spomespecificException1 ex){
 //logging and other stuff
}catch(spomespecificException2 ex){
 //logging and other stuff
}catch(Exception ex){
 //logging and other stuff
}

should i append the exception catch to the stack

Richard Banks
  • 2,946
  • 5
  • 34
  • 71
  • This really depends on the context of the situation and is probably fairly subjective as well. I don't think you will really be able to say yes or no without more detail. – Andy Rose Oct 13 '11 at 13:50
  • Related thread - http://stackoverflow.com/questions/183589/c-windows-forms-best-practice-exception-handling – KV Prajapati Oct 13 '11 at 13:51
  • My general rule-of-thumb is to catch general exception at a point where it would abort a unit-of-work but let the process continue. That is, if I have an order processing service, and I am placing an order, i would want to catch any exception from placing an order so i don't bring down the service, but anything deeper than that should not be caught and consumed. In my mind that's congruent with John's Handle/Fix definition. But that's me... – James Michael Hare Oct 13 '11 at 13:55
  • @JamesMichaelHare: How do you know that bringing down the service might not be the right thing? Maybe the service is so damaged that when it's not throwing exceptions, it's corrupting orders. Shutting down the service (and notifying you so you can fix it ASAP) might be exactly the right thing to do. – John Saunders Oct 13 '11 at 14:17
  • @John: That's always an option. But it can also lead to dire financial consequences if it cancels other orders currently in process concurrently. We report all the exceptions to our monitoring tools along with all the perf counters so we can see the state of our application from our dashboard including exceptions thrown. – James Michael Hare Oct 13 '11 at 14:31
  • @JamesMichaelHare: how do you know you won't suffer greater consequences when Order A corrupts Orders B, C and D? I'd persist the information necessary to make the orders, then crash and start over (without Order A, which I would put into the "penalty box" until the problem is fixed). – John Saunders Oct 13 '11 at 14:37
  • @John: I see the value in what you're saying, many times we do put bad orders (due to bad input data) in an exception table to be worked, but terminating and restarting the whole service may not always be an option if time-to-market is a consideration due to delays for non-bad orders. I agree the most pure thing to do is crash and restart, but that could have bad consequences as well. I should ammend that I wouldn't want to catch and consume clr exceptions, as you are correct those are very indicative of a very bad state. – James Michael Hare Oct 13 '11 at 15:06
  • @John Saunders: A fundamental problem with .net, Java, and some other systems, is that they have lots of comparatively useless exception types and lack some fundamental ones: OperationFailedStateUnchangedException, FailedOperationChangedStateException, ObjectCorruptException, and SystemStateCorruptException. Code should often catch and swallow less severe types, or sometimes "promote" them. Code should only demote exceptions if it's going to eliminate the changed or corrupted state. Code should not try to continue after SystemStateCorruptException. – supercat Oct 13 '11 at 16:51
  • @John Saunders: In practice, a lot of the exceptions that occur are going to indicate that an operation failed without changing anything, and jettisoning the present unit of work is exactly the right thing to do. Too bad I don't think there's anything better one can do than guess either optimistically or pessimistically which category some particular InvalidOperationException should fall into. – supercat Oct 13 '11 at 16:56
  • @supercat: depending on what went wrong, there's no way to know which of your proposed exceptions to throw. I'm not talking about corruption meaning the program changed something. I mean corruption in the sense of you don't know what did or did not get changed; or memory corrupted; or what. – John Saunders Oct 13 '11 at 18:25
  • @John Saunders: In most cases, if one calls a routine which correctly throws one of the indicated exceptions, one would pretty well know whether it should be escalated. To allow code to know when to deescalate, one would have to know what objects were possibly changed or corrupted. My preferred way of handling this would be for the exception to include a virtual IsResolved property, but detailing that would go beyond the comment size limit. – supercat Oct 13 '11 at 20:14
  • @supercat: sorry, you're presuming a level of control which doesn't exist in the real world. – John Saunders Oct 13 '11 at 20:15
  • @John Saunders: I know the exception hierarchies used by the .net and Java are what they are, and I can't go into a time machine and rework them to something useful. That doesn't mean that when designing new classes one shouldn't define exceptions to go with them that do indicate, to the extent possible, the system state when they are thrown. – supercat Oct 13 '11 at 20:27

4 Answers4

7

You shouldn't be catching those exceptions at all, in general. Don't catch exceptions that you don't actually know how to handle.

"Handle" means fix. If you can't fix the problem, or if you can't add additional information, then don't catch the exception.

John Saunders
  • 160,644
  • 26
  • 247
  • 397
  • That isnt true. In a lot of cases you want to catch the exception to exit gracefully, inform the user or inform the admin. Its quite rare you just want the exception to go unhandled. – Tom Squires Oct 13 '11 at 13:51
  • What about catching for logging purposes? – msmucker0527 Oct 13 '11 at 13:51
  • @Tom: But in that case, you are handling it, or you would catch-and-rethrow. I think the main point is never consume an exception you can't fix (fix meaning handle correctly and continue). – James Michael Hare Oct 13 '11 at 13:52
  • If you have to catch the exception in order to log it, then it should be done as close to the top of the call stack as possible. And, in many cases, the framework will log for you. This is the case with ASP.NET, for instance. And be sure that your logging is of the sort that will trigger server-monitoring tools like SCOM or Big Brother. – John Saunders Oct 13 '11 at 13:53
4

It depends on the situation and how far up the stack you want to let an exception bubble before being caught.

There are certainly reasons for and against but without details specific to your situation it's impossible to tell.

So, is there a general "rule" about it? no.

NotMe
  • 87,343
  • 27
  • 171
  • 245
  • 1
    I would argue (and frequently do) that the general rule is don't catch exceptions unless you know how to handle them, so, in general, don't catch exceptions. – John Saunders Oct 13 '11 at 13:50
  • @John Saunders What about catching them so you can throw your own custom exceptions – Richard Banks Oct 13 '11 at 14:13
  • 1
    @RichardBanks: sure, except there is almost no need for custom exceptions. Use them only if a caller will be catching your exception explicitly. If the caller code will react the same to `MyCustomException` as it will to `InvalidOperationException`, then there is no need for `MyCustomException`. If you're just trying to customize the `Message`, then `String.Format` takes care of that. – John Saunders Oct 13 '11 at 14:16
  • @John Saunders doesnt creating custom exceptions mean less code though. If a method has to handle 5 exceptions then why not wrap the exception thrown in a custom exception then the caller only has to trap the one custom exception. – Richard Banks Oct 13 '11 at 16:26
  • @RichardBanks: Then why bother trying to catch all of the different exception types, just catch Exception? – NotMe Oct 13 '11 at 17:55
  • @RichardBanks: that's _if_ a method has to handle 5 exceptions. My point is that, usually, the method shouldn't be handling _any_ exceptions. Note that I said "almost" no need. If the code actually _does_ need to do something different for your exception than it would for `Exception`, then create a custom exception. But if they would be just as well off catching `Exception`, then don't create a custom exception. – John Saunders Oct 13 '11 at 18:22
1

The code you have posted is fine if you want to do some specific handling relating to that exception - which you would want to do in one of the other catch blocks. A good example might be when you are trying to connect to an SQL database and you can handle the different error messages in different ways.

Also, remember there is a "finally" block you can add to the end to do all clean up (and common) handling code, but you will not get exception information in there

musefan
  • 47,875
  • 21
  • 135
  • 185
0

Exceptions do generally happen especially if your accessing something outside your application like connection errors etc.

If you want to filter out the type of exceptions and do something different for each particular type, then there's nothing wrong with doing this.

A better coding practice would be preventing these exceptions from happening in the first place.

Jonats
  • 391
  • 2
  • 7