Thursday, February 28, 2013

Tips and Tricks of Exception Handling in .Net - Part 3

This is the continuation of my article Tips and Tricks of Exception Handling in .Net - Part 2

Fail Fast Method: There are situations where your application's state is very bad and no code should be executed further - not even finally block code and your application needs to be closed immediately. How you do this?
           The answer is Environment's FailFast method. As the name suggests, this  is a special method which causes your application to fail immediately. It also creates a dump and event viewer entry.
 try 
 {
     Environment.FailFast("Text to be logged");
 }
 finally
 {
     Console.WriteLine("This finally block will not be executed.");
 }
Compile above code and execute the generated .exe you will see the following windows prompt, which you get usually when your application is having unhandled exception.















Process.GetCurrentProcess().Kill() vs Environment.FailFast(""): The finally block will not be executed even if you use Process.GetCurrentProcess().Kill() and this also ends your application immediately, then how it differs from FailFast? well, the difference is - FailFast will create a dump and event viewer entry but killing the current process will not.

Note: The both should be used with extensive care. In real-world these are required very rarely.


Corrupted State Exceptions (CSE): These are the exceptions which cannot be catched. Behind the scene Environment's FailFast method throws one of these exceptions. Hence, it cannot be catched and your application ends with an unhandled exception.

Here is the explaination of CSE by Jffrey Richter's words:
      Usually, CLR considers few exceptions thrown by native code as Corrupted State Exceptions, because they are usually the result of a bug in the CLR itself or in some native code for which the managed developer has no control over. Here is the list of native Win32 exceptions that are considered CSEs:

EXCEPTION_ACCESS_VIOLATION        EXCEPTION_STACK_OVERFLOW
EXCEPTION_ILLEGAL_INSTRUCTION     EXCEPTION_IN_PAGE_ERROR
EXCEPTION_INVALID_DISPOSITION     EXCEPTION_NONCONTINUABLE_EXCEPTION
EXCEPTION_PRIV_INSTRUCTION        STATUS_UNWIND_CONSOLIDATE

By default, the CLR will not let managed code catch these exceptions and finally blocks will not execute. However, Individual managed methods can override the default and catch these exceptions by applying the System.Runtime.ExceptionServices.HandleProcessCorruptedStateExceptionsAttribute to the method. In addition, the method must have the System.Security. SecurityCriticalAttribute applied to it. You can also override the default for an entire process by setting the legacyCorruptedStateExceptionPolicy element in the application’s Extensible Markup Language (XML) configuration file to true. The CLR converts most of these to a System.Runtime.InteropServices.SEHException object except for EXCEPTION_ACCESS_VIOLATION, which is converted to a System.AccessViolationException object, and EXCEPTION_STACK_OVERFLOW, which is converted to a System.StackOverflowException object.

Note: Even with the attribute HandleProcessCorruptedStateExceptions, we cannot handle the following exceptions, for a given reason:

  • StackOverflowException - As this is a hardware failure and there is no more stack available for further processing (Thanks Abel Braaksma for pointing this out).
  • ExecutionEngineException - It occurs because of heap memory corruption and hence cannot be handled further (Reference).

Summery:
  • Structured Exception Handling - This is the exception handling mechanism which is offered by Microsoft Windows and .Net Framework Exception Handling is built on the top of it.
  • What can be thrown? - The CLR allows an instance of any type to be thrown. But CLS mandates to throw only the Exception derived objects. The C# compiler allows to throw only exception derived types.
  • Throw different exception than the originally thrown one, when you want to maintain the meaning of a methods contract.
  • Make sure to set original exception as inner exception when you throw a different exception.
  • Constrained Execution Regions - Make sure that your catch or finally block will never throw an exception by making use of CER. You can use it by calling RuntimeHelpers's PrepareConstrainedRegions method and applying ReliabilityContract attribute wherever required.
  • The C# language automatically emits try/finally blocks whenever you use the lock, using, and foreach statements.
  • Call Environment's FailFast method when you want your application to be closed immediately and put a dump with event viewer entry.

Thursday, February 21, 2013

Tips and Tricks of Exception Handling in .Net - Part 2


This is the continuation of my article Tips and Tricks of Exception Handling in .Net - Part 1


Constrained Execution Regions:  Usually, we write code to recover from an exception in catch block. Now what if the catch block itself throws an exception?

Well, you can say that we can use another try/catch block inside our catch. But are you sure you properly recovered from the corrupted state or you are just ignoring it and going forward. This all depends on the actual implementation though, we should always try our level best to keep our application in proper state. In other words, the application should never-ever contain a corrupted state. The CLR provides CER to handle such a situation.

The CER allows you to compile all the code written in your catch and finally block prior to the try block. Hence, if there is any chance of failure in catch block, that happens immediately there by not letting your application with the corrupted state. Here is a sample code describing it from the book CLR via C#.
        public static void Test()
        {
            // Force the code in the finally to be eagerly prepared
            RuntimeHelpers.PrepareConstrainedRegions();
            try
            {
                Console.WriteLine("In try");
            }
            finally
            {
                // MyType's static constructor is implicitly called in here
                MyType.Foo();
            }
        }

        public class MyType
        {
            static MyType()
            {
                Console.WriteLine("MyType Constructor Called");
            }

            // This attribute is required for PrepareConstrainedRegions to work.
            [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
            public static void Foo() { }
        }
If you execute this code you will get the following output:
MyType Constructor Called
In try
As you can see in the output, finally block is compiled prior to the try block there by executing the MyType's static constructor first. All we need to do is call RuntimeHelpers's PrepareConstrainedRegions method prior to try block and apply ReliabilityContract attribute to the methods which needs to be compiled in prior.

Refer this link for more information.

Automatic Generation of try/finally: Ensuring that cleanup code always executes is so important that many programming languages offer constructs that make writing cleanup code easier. For example, the C# language automatically emits try/finally blocks whenever you use the lock, using, and foreach statements. The C# compiler also emits try/finally blocks whenever you override a class’s destructor (the Finalize method). When using these constructs, the compiler puts the code you’ve written inside the try block and automatically puts the cleanup code inside the finally block. Specifically,
  • When you use the lock statement, the lock is released inside a finally block.
  • When you use the using statement, the object has its Dispose method called inside a finally block.
  • When you use the foreach statement, the IEnumerator object has its Dispose method called inside a finally block.
  • When you define a destructor method, the base class’s Finalize method is called inside a finally block.
These are the words of Jeffry Richter(from the book CLR via C#). There is another interesting point which he did not mentioned in the book, but I found it in this stackoverflow question. Here pb noticed that iterator block generates try-fault block instead of  try-finally. 

Now what is this try-fault? can we use it in C#?
       The answer is given in the same SO question by Steve Steiner. In his words, a Finally block always executes on frame exit. A fault block executes only if an exception is unwound past the frame.. That means, the fault block executes only if there is an exception. Now again, another question comes into mind i.e.

If fault block executes only if there any exception in the try block, then whats the difference between fault and catch?
      While researching about this, I got this SO link. Here, the accepted answer says this:
catch - I need to do something with the exception object when an exception occurs.
fault - I don't need the exception object, but I need to do something when an exception occurs.
finally - I don't need the exception object, but I need to do something before the end of the function.

Here is another interesting article regarding this.

Before ending this section, there is another thing which I need to mention. That is about exception filter - Now what is this new concept again? well, here is the answer from previously linked SO post:

It is similar to a catch block but can run arbitrary code to determine whether it wants to handle the error, rather than just matching on type. This block has access to the exception object, and has the same effect on the exception stack trace as a catch block.

Oh! I forgot about the question, can we use fault in c#? You may already got the answer, if not here is it.
        Currently, no languages provide support for fault. However, Bart De Smet shown a way to use it in c# here (You can also produce it using reflection as shown in MSDN, but this is a big pain). The c# also doesn't support filter handler but VB.Net supports it.


Topics will be covered in Part - 3:  FailFast method and CSE(Corrupted State Exceptions).

Read Part - 3

Tuesday, February 19, 2013

Tips and Tricks of Exception Handling in .Net - Part 1

This week I was reading Exceptions and State Management chapter of the book CLR via C# and learnt some interesting stuffs. I did some experiment and summarized few points which I would like to share. OK, lets start them one by one.

Structured Exception Handling: The .Net Framework Exception Handling is built using this mechanism which is offered by Microsoft Windows. It mainly introduces 3 blocks namely try, catch and finally. 
Where,
  • try - is like a guard where we write the code which might cause an exception to be raised.
  • catch - is a block which is intended to handle an exception which is raised in try block.
  • finally - is a block which is intended to write a cleanup code.
Refer this link for more information regarding SEH.

What can be thrown?
       The CLR allows an instance of any type to be thrown. But CLS mandates to throw only the Exception derived objects. The C# compiler allows to throw only exception derived types.

Some points about try, catch, finally and throw in C#:
  • try cannot stand by itself. Means, try block musht be followed by catch or finally block.
  • You can write multiple catch blocks for a single try block but you cannot write multiple finally blocks.
  • You can write catch in 2 ways:
          1. Without specifying any exception type.
          2. By specifying an exception type.
  • finally  block always executes, even if try block is having a return statement. However, you cannot write return statement in this block!
The points which I mentioned above is the basic things and compiler itself teaches you if you are not aware of it. But there are some interesting things which is related to these points which I will address later on this post.

catch vs catch(Exception ex): These both are same and used to handle generalized exceptions.
The first one can be written like this:
try
{
}
catch
{
   throw; // Throws any and all exceptions without altering the stack trace.
}
and the later one can be written like this:
try
{
}
catch(Exception ex)
{
   throw; // Throws any and all exceptions without altering the stack trace.
}
The above two code fragments will be having same behavior(but you will get compiler warning for the second one, since the variable ex is not used in the block).

Note: This is same only if the CLR version is 2.0 and above - Prior to that the later one will catch only CLS-Compliant Exceptions. In version 2.0 of CLR, Microsoft introduced RuntimeWrappedException class which is derived from Exception so it is CLS-compliant exception type. This class contains a private field of type Object. In version 2.0 and above  of the CLR, when a non-CLS compliant exception is thrown the CLR automatically constructs the instance of RuntimeWrappedException and initializes its private field to refer to the object that was actually thrown.

When we need to log the exception information or do some other operations based on the values of exception object, then we can use the later one. Otherwise first one will be fine to delegate the exception to the caller.

Be Careful with throw vs throw ex

Now lets alter the second code like this:
try
{
}
catch(Exception ex)
{
   throw ex; // Throws any and all exceptions by altering the stack trace.
}
Note the throw statement above. This makes a lot of difference to the first code(i.e. throw;). When an exception variable  is specified along with the throw statement, the stack trace of the exception will be altered. Here we are lying the client code by changing the actual location of the exception! Hence, it will be difficult to debug such codes and therefor it is not the preferred or recommended way.

Here is an example code to check this behavior.

Throwing different exception than the catched one: We can also throw a different exception than the one which is catched by catch clause. This is useful when we need to maintain the meaning of a methods contract. Ex:
    
    // Source: CLR via C# by Jeffrey Richter
    internal sealed class PhoneBook
    {
        private string pathname;

        public string GetPhoneNumber(string name)
        {
            string phone;
            FileStream fs = null;
            try
            {
                fs = new FileStream(pathname, FileMode.Open);
                // Code to read from fs until the name is found goes here.
            }
            catch (FileNotFoundException ex)
            {
                // Throw different exception containing the name, and
                // set the originating exception as the inner exception.
                throw new NameNoteFoundException(name, ex);
            }
            catch (IOException ex)
            {
                // Throw different exception containing the name, and
                // set the originating exception as the inner exception.
                throw new NameNoteFoundException(name, ex);
            }
            finally
            {
                if (fs != null)
                    fs.Close();                
            }
        }
    }
As you can see in the above code GetPhoneNumber's contract is to find and return the phone number. Hence, in this case a meaningful exception will be NameNoteFoundException(Off-Course, this should be of type Exception derived).

We can see this approach in many places of FCL like type initialization, smtp connection, dealing with entity framework context etc.

Note: This should be used with extensive care. Improper usage of this will make the code horrible to maintain!

You can also add information to the exception variable before throwing it. Like: ex.Data.Add(anyObject);


Topics will be covered in Part - 2: CER(Constrained Execution Region) and Automatic Generation of try/catch/finally.

Read Part -2