O'Reilly logo

ASP.NET Cookbook by Geoffrey T. LeBlond, Michael A Kittel

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

7.1. Handling Errors at the Method Level

Problem

You’re uncertain how to best organize your code to handle errors at the method level. In particular, you’d like to take advantage of .NET structured exception handling for dealing with errors, but you’re not sure how to best implement it.

Solution

If potential errors are recoverable in the routine

Use a combination of Try...Catch blocks as a retry mechanism for error handling.

If useful information can be added to the exception

Create and throw a new exception with the added information.

If cleanup is required

Perform it in the finally block.

If potential errors are not recoverable in the routine

Recovery should be handled by the calling routine and its error-handling structure.

Discussion

Because .NET structured exception handling is so good, we recommend that you use it, or at least consider using it, with every method that you write. There are a number of ways to implement its functionality.

Basic syntax of Try...Catch...Finally

To begin with, here is the syntax of a .NET Try...Catch...Finally block in VB and C#:

                  Basic syntax of Try...Catch...Finally
Private Sub anyRoutine( )

  Try
                      'Routine code in this block

                    Catch err As Exception
                      'error handling in this block

                    Finally
                      'cleanup performed in this block

                    End Try
End Sub  'anyRoutine

Basic syntax of Try...Catch...Finally
private void anyRoutine( )
{
  try
                    { 
                       // Routine ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required