Thursday 12 January 2012

Structured Exception Handling in C#/VB.NET

    Structured Exception Handling (SEH) allows you enclose code that can possibly encounter errors or raise exceptions within a protected block. You can define exception handler filters that can catch specific exception types thrown by the code within the protected block. Lastly, you can create a block of cleanup code that guarantees to execute always – both when an exception is thrown as well as on a normal execution path.
    C# and VB.NET supports the following SEH keywords to raise and handle exceptions:
 try
throw
catch
finally
    To facilitate structured exception handling in C#/VB.NET, you typically enclose a block of code that has the potential of throwing exceptions within a try block. A catch handler associated with the exception that is thrown catches the exception. There can be one or more catch handlers and each catch handler can be associated with a specific exception type that it can handle. The catch blocks are generally used to gracefully inform the user of the error and to possibly log the error to a log file or to the system event log. You can
optionally have a finally block that contains code that will execute both when an execution is thrown as well as on a normal execution flow. In other words, code within the finally block is guaranteed to always execute and usually contains cleanup code. So how can you raise an exception? . To do that your code needs to throw an exception using the throw keyword. The exception that is thrown is an object that is derived from the
System.Exception class. We’ll examine this class in detail in the next section. Now let’s consider a normal execution flow in a program where no error occurs within the try block.
Explanation in C#


Explanation in VB.NET
   
  In this case, the code within the try block does not throw an exception and therefore, the code within the catch block never executes. Once the code within the try block completes, the execution path resumes by executing the code in the finally block. As mentioned earlier, the code within the finally block executes whether or not an error had occurred.  Let’s turn our attention to a scenario where the code within the try block raises an exception.
Explanation in C#
 
Explanation in VB.NET
 
   When the exception is thrown, execution flow is transferred to the catch block that is capable of handling the exception thus skipping the rest of the code below the line that threw the exception in the try block. The code in the catch block handles the exception appropriately and then execution flow moves to the code in the finally block.