12

I am creating asp.net web apps in .net 3.5 and I wanted to know when to use and when not to use Try Catch Finally blocks? In particular, a majority of my try catch's are wrapped around executing stored procs and populating textfields or gridviews? Would you use Try Catch EVERYTIME when you execute a stored proc and populated a data display control?

My code block usually looks like:

    protected void AddNewRecord()
    {
        try
        {
           //execute stored proc
           // populate grid view controls or textboxes
        }
        catch (Exception ex)
        {
           //display a messagebox to user that an error has occured
           //return
        }
        finally
        { }
   }
user279521
  • 4,779
  • 21
  • 78
  • 109
  • also see this: http://stackoverflow.com/questions/505471/how-often-should-i-use-try-and-catch-in-c – 0x49D1 Jul 06 '10 at 13:19
  • Check the book "CLR via C#", 3rd edition, by J. Richter. It covers the exception handling concepts in great detail, and is definitely a good reference. – ileon Jul 06 '10 at 16:36

7 Answers7

11

The answer is "it depends".

You might want to use a try{...} catch {...} around every atomic operation so that if there is a problem you can roll back to the last good state (using transactions). This may be one or several stored procedures - it depends on your application.

If you are trapping the exception, make sure you are explicit in which exceptions you catch. You shouldn't have catch (Exception ex) or catch() - known as "catch all" exception handling - but have specific catch statements like catch (IndexOutOfRangeException ex) (for example) instead.

However, if you can't handle the exception or there's nothing you can do to clean up, then you shouldn't trap it.

ChrisF
  • 134,786
  • 31
  • 255
  • 325
  • What do you mean by "atomic" operation? – user279521 Jul 06 '10 at 13:01
  • 3
    @user279521 - "atomic" - like an atom in that it can't be divided any further. It might have a number of steps but each step has no meaning if carried out on it's own. For example, if you fix a bug in your code but that requires edits to a number of classes the check in of all the files is said to be atomic as just checking in one has no meaning. – ChrisF Jul 06 '10 at 13:05
  • 1
    @Chris S - if you're going to get pedantic ;) It's from the Greek, ἄτομος (átomos), meaning uncuttable/indivisible. – ChrisF Jul 06 '10 at 13:55
4

You should only use try catch, when you intend on handling the exception in the catch block. What I mean by handle is, log the error, choose a different path because of the error etc. If you merely intend on re-throwing it, there is no point in having try catch.

kemiller2002
  • 113,795
  • 27
  • 197
  • 251
  • 1
    If you want to log the error, there is no need to catch the exception at the point where it occurred--instead you can have a catch at the exit point from your code which logs any exceptions that occur anywhere in your code. – Polyfun Jul 06 '10 at 14:47
  • You make a good point, but I think it largely depends on the overall architecture of the application. Really I was just providing it as an example of when to possibly use a try catch. – kemiller2002 Jul 06 '10 at 14:57
  • What if an object's invariants rely upon having all the code within a block execute? I would think that in such a case, the code should be guarded by a block which will expressly invalidate the object if an exception occurs at time when the object's invariants may not hold. If the exception will cause calling code to abandon the corrupt object, the act of abandoning the corrupt object will resolve the problem. If the calling code tries to use the corrupt object, such attempts should cause exceptions thus forcing further unwinding until things are resolved or they die altogether. – supercat May 20 '13 at 21:42
1

As others have said, it depends. I tend to use try/catch/finally blocks in two situations:

  • I need to handle the Exception in some way other than simply re-throwing it.

  • I need to clean up some resources in the finally block.

Other than those two situations, I let the calling code handle any Exceptions that might happen.

Justin Niessner
  • 242,243
  • 40
  • 408
  • 536
1

In addition to what others have said, be sure to avoid doing this:

    try
    {
        throw new ApplicationException("Fake sql ex");
    }
    //catch and do nothing.  swallowing exceptions
    catch(Exception){ }                 
P.Brian.Mackey
  • 43,228
  • 68
  • 238
  • 348
0

Most of the time you should not be catching exceptions. Some places where it does make sense to catch an exception e.g.,

When you can recover from that specific exception. When you need to log it or report it (e.g,. to the user)--usually at the top level in your code. When the caller of your code can not handle exceptions, so you need to convert them into some other error format.

Also, the using block statement can be used to actually call Dispose on IDisposable objects, which removes the need for try...finally.

Polyfun
  • 9,479
  • 4
  • 31
  • 39
  • What if I want to display a messagebox to the user "An error occured while loading data" ? How would I accomplish that without a Try Catch block? – user279521 Jul 06 '10 at 13:01
  • You need a try-catch to pop up the message box with the exception – Dan McClain Jul 06 '10 at 13:03
  • As I said, you only need this at the top level of your code: "When you need to log it or report it (e.g,. to the user)--usually at the top level in your code." – Polyfun Jul 06 '10 at 14:17
0

What is the Exception you are expecting from the stored proc? Providing you don't use pokemon exception handling and know exactly what your application is expected to do, anything that doesn't fit the specific Exception you want to to catch will be caught by the Application object.

In other words don't use catch {} or catch (Exception), but specialized exception handling:

catch(SqlException e)
{
   // Log stacktrace and show a friendly error to your user
}

The Application.Error event is where unexpected behaviour should be caught and is easier to trace than simply having a customer return to you saying "my fields aren't displaying anything".

Community
  • 1
  • 1
Chris S
  • 64,770
  • 52
  • 221
  • 239
  • No particular exception is expected, but "just to be safe", I have been told in the past that all database calls should be wrapped in try catch blocks. – user279521 Jul 06 '10 at 13:24
  • But you don't need to catch Exception. You can happily catch all SqlExceptions or whichever database you are using. If something else is thrown you probably will want to know about it instead of it dying silently – Chris S Jul 06 '10 at 13:42
0

Use "try catch" within the innermost loop that should keep executing when a particular exception occurs. Be mindful that if you have a loop that executes 10,000 times and an exception occurs on e.g. the tenth repetition which won't affect the other 9,990 it may be useful to catch the exception and let the loop keep going. On the other hand, if the exception indicates a fault that suggests the 11th, 12th, 13th, etc. times through the loop are also going to fail, it would be much faster to let the exception kill the loop than to keep retrying an operation that isn't going to work.

supercat
  • 77,689
  • 9
  • 166
  • 211