January 23, 2014

Exception Handling : The use of Try and Catch

New to C# ? Start from the beginning : Kick-Start C# : Your first program
Previous Post : Advanced CSharp Part 4 : Delegates and Events
Next Post : Threads in C# : Part 1

You are asked to write a program and then deliver it to your client. You have a nice looking User Interface and the next big thing that happened is that, your client provided a faulty input mistakenly and the program crashed! How often does that happen? Very often indeed. Exception handling can save you from such embarrassment and proved to be very developer friendly.

An Exception is basically an error that happens during your program's execution. But there is a fine line between an "error" and an "exception". When you forget to close a curly brace or put a using statement or a semicolon at the end, your compiler shows an error at compile time that "Hey you forgot or missed this and that!". Consider the case where you have a divide operation and the user mistakenly divides by zero! You cannot determine that at compile time, rather your program should be intelligent enough to determine that at run time! If such an operation is not dealt differently, your program is bound to crash.

So lets get familiar with the exception handling ecosystem.
  • The programmer anticipates that certain operation(s) is prone to errors.
  • Exceptions are raised, or thrown, when errors are encountered.
  • The anticipated portion of the program is written inside a try block.
  • When an error is encountered, the normal flow is interrupted and the control is given to the nearest exception handler- the catch block.
  • The .NET framework provides some exception handling classes. But you can build your own exceptions.
  • Three keywords are associated with exception handling - try, catch and finally.
Here is a working example.

using System;

namespace Spells
{
    class Program
    {
        public static void Main(string[] args)
        {
            int a=10, b=0, result=0;
            try
            {
                // piece of code that you anticipate can generate error
                result = a / b;
            }
            catch (Exception ex)
            {
                // deal with the exception
                // generally programmers show error message and wind up system resources inside this block
                Console.WriteLine("Exception handled. Message : {0}", ex.Message);
            }
            finally
            {
                // this block is always executed, with or without exceptions
                Console.WriteLine("Result {0}", result);
            }
            Console.Read();
        }
    }
}
The code is self-explanatory, necessary comments have been given in the snippet. If you type the code, a short-cut way to write try-catch is to write the word "try" and press "Tab" twice.
This is the output console.
The 1st line in the console window is line 19 in the code, while the 2nd console window line is line 24 in the code. Makes sense? The catch block optionally takes an argument of type Exception. Go to this MSDN link and scroll down to the bottom. You will find an Exception hierarchy where all the sub classes under Exception base class are mentioned. You can specify which type of exception you are trying to handle in the catch argument or you can specify the base class Exception type to catch all types of exceptions in a single catch block. If you remove all the try-catch-finally things and run the same code, your program will stop running in the middle, imagine that happening to a software product that you developed leaving no clue to the customer. The Message property is a useful property. I have used that property at line 19 to show what type of exception my program has encountered.

The basic essence that we get here is that, like other things in .NET, Exceptions are also objects. The .NET library has defined a whole lot of exception classes. Under these circumstances, you as a programmer need to be very specific about what type of exception you want to catch.
Consider the following two cases:
Case 1
Case 2

Can you explain what's the difference? The ArithmeticException is a superclass to DivideByZeroException class. So whatever errors that are related to Arithmetic operations, will be caught by this class, leaving the DivideByZeroException block unreachable. While writing catch block, you need to write hierarchically low descendents first. Since DivideByZeroException class is a subclass of ArithmeticException class, the Case 1 is appropriate while Case 2 generates a compile time error.

Custom Exception Class: You are eligible to write your own custom Exception classes. You will have to subclass the System.Exception and then build your own custom classes. Let's see a working example in action.

using System;

namespace Spells
{
    class UseOfSlangsException : Exception
    {
        public UseOfSlangsException()
            : base("Obscene word used")
        {
            this.HelpLink = "www.behave-well.net";
        }
    }
    class Program
    {
        public static void Main(string[] args)
        {
            string input;
            try
            {
                input = Console.ReadLine();
                if (string.Equals(input, "jackass", StringComparison.OrdinalIgnoreCase))
                {
                    throw new UseOfSlangsException();
                }
                else Console.WriteLine("Its clean!");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Hey! You have been warned. {0}\nHelp link {1}", ex.Message, ex.HelpLink);
            }
            finally
            {
                Console.WriteLine("Finally block");
            }
            Console.Read();
        }
    }
}
This is the output window.
 If you go to the MSDN link given above, you will see that the Exception class has some overloaded constructors, one of them taking a string message. This string message is passed through the Message property as seen on line 29. The custom exception class is on line 5, you are familiar with the notations of subclassing in C#. The constructor at line 7 takes no arguments, just passes a string to the base class constructor. The HelpLink is a property field. Observe line 23 where we create a new exception object of type UseOfSlangsException. This statement triggers the exception handling mechanism in the .NET framework and the code control is shifted to the catch block.

What have we learned so far? We have learned about the generic Exception class. We are also now able to build our custom exception handling classes. I really hope I have made these things clear to you. Happy Coding!