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
{ }
}
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)orcatch()– known as “catch all” exception handling – but have specific catch statements likecatch (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.