views:

306

answers:

7

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
        { }
   }
+6  A: 

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() - know as catch all exception handling - but have catch (IndexOutOfRangeException ex) (for example).

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
What do you mean by "atomic" operation?
user279521
http://en.wikipedia.org/wiki/Atomic_operation
phsr
@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
@phsr - thanks for the link!
ChrisF
user279521
Quark operations
Chris S
@Chris S - if you're going to get pedantic ;) It's from the Greek, ἄτομος (átomos), meaning uncuttable/indivisible.
ChrisF
A: 

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.

ShellShock
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
You need a try-catch to pop up the message box with the exception
phsr
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."
ShellShock
+3  A: 

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.

Kevin
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.
ShellShock
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.
Kevin
+1  A: 

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
As an aside, `using` is basically a `try-finally` block for cleaning up resources (via `Dispose`).
Brian
@Brian - Correct, but not everything that needs cleaned up always implements IDisposable (or Dispose).
Justin Niessner
+1  A: 

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
Pokemon Exception Handling: Gotta catch 'em all!
Pierre-Alain Vigeant
A: 

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".

Chris S
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
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
A: 

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