Monday, March 31, 2008

Try, Catch (and Finally)

The purpose of the try, catch, and finally blocks is to trap unexpected exceptions. A common usage is to obtain and use resources in a try block, trap exceptional circumstances in a catch block, and release the resources in the finally block. With a combination of input validation controls and keeping expected errors in mind while coding, the use of try-catch-finally can minimize the possibility of an ASP.NET application crashing.

Try Clause
  • The try block encloses the code being executed.
  • The exceptions may be thrown on completion of this block.
  • There is only one Try block per try-catch-finally combination.

Catch Clause
  • The catch blocks are optional.
  • Thess blocks catches the exceptions.
  • The catch blocks are executed only if exceptions occur.
  • The catch blocks may be defined without arguments though not recommended.
  • It is suggested to have the object argument derived from System.Exception
  • There may be more than one specific catch clause in the same try-catch statement.

Finally Clause
  • The finally block is optional.
  • When used, finally block is executed without fail.