8.1. Handling Errors at the Method Level


You’re uncertain how to 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 unsure how to best implement it.


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.


Because .NET structured exception handling is so good, we recommend you use it, or 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#:

	Private Sub anyRoutine( )
		'Routine code in this block

		Catch exc As Exception
		'error handling in this block

		'cleanup performed in this block

		End Try
		End Sub 'anyRoutine

 private void anyRoutine( ) { try { // Routine code in this block } catch (Exception exc) ...

Get ASP.NET 2.0 Cookbook, 2nd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.