Friday, October 7

Exception Handling using C-Sharp Language

Exception occurs when user tries enters an invalid value like we have provided user with an application to enter an interger and he/she enters a string value as in input. If the exception is not handled at this point then your application will crash ultimately. Exceptions are unforeseen errors that happen in your programs. Most of the time, you can, and should, detect and handle program errors in your code. In lower level languages exceptions are not being handled. But if you move to the higher level language like c-Sharp, java. Microsoft provides special techniques to the developer so by using these methods properly you can protect your application from being crashed.

All the exceptions occur at the run-time. you can an exception a run-time error. Common run-time errors are data copying from one drive to another and you receive a dialog box which says not enough memory. Exception crashes the program you will be looking at the program that it is working fine but actually not. However, there are times when you don't know if an error will occur. For example, you can't predict when you'll receive a file I/O error, run out of system memory, or encounter a database error. These things are generally unlikely, but they could still happen and you want to be able to deal with them when they do occur. This is where exception handling comes in. System.Exception class provides several methods to handle exception.
Identifying the exceptions you'll need to handle depends on the routine you're writing. For example, if the routine opened a file with the System.IO.File.OpenRead() method, it could throw any of the following exceptions:

  • ArgumentException
  • NullReferenceException
  • FormatException
  • OverflowException
  • PathTooLongException
  • DirectoryNotFoundException
  • UnauthorizedAccessException
  • FileNotFoundException
  • NotSupportedException

when Exception occurs you are required to throw this exception. by this try and catch blocks are used.Try and catch statements works same like if else Statements.C-sharp exception handling program is the best example to get the concept of try and catch block.  Fortunately, we've included a finally block in Listing , which will always be executed. That's right, regardless of whether the algorithm in the try block raises an exception or not, the code in the finally block will be executed before control leaves the method.A finally block is not required and you may ask what happens if you just put code after the catch block. True, under normal circumstances, if the exception is caught, all code following the catch will be executed. However, try/catch/finally is for exceptional circumstances and it is better to plan for the worst to make your program more robust. For example, if one of the catch handlers rethrew an exception or caused another exception, the code following the catch block (not in a finally block) would never be executed. Also, if you don't catch the exception at all, program flow would immediately do a stack walk looking for an exception handler that fits and the code following the catch blocks would not be executed. Since there is too much potential for code in an algorithm to not be executed, a finally block is your insurance for executing those critical actions you need. Finally must executes after every catch or try block. In the above example if we put the code which is printing value on the screen  in finally block then it will be executed after every try or catch block. The code which we want to parse or check whether it is a valid code or not. first of all it is put into try block and if the try block gives success then it will not allow to execute the catch block. you can check this operation by Displaying any Statement like Try Block is executed and Catch Block is Executed in the respective blocks. and more over there is another block which is called finally block. which must be executed after try block. and one more important thing you can have only one Try Block within a project and have multiple blocks of catch within the same project. An exception can leave your program in an inconsistent state by not releasing resources or doing some other type of cleanup. A catch block is a good place to figure out what may have gone wrong and try to recover, however it can't account for all scenarios. Sometimes you need to perform clean up actions whether or not your program succeeds. These situations are good candidates for using a finally block.
Here is an example which will illustrate exception handling.

/////////////////////////////////////////////////////////////////////////// Begins /////////////////////////////////////////////////////////////////////////////

class Program
        static void Main()
            int decimalValue = 0;
            bool exceptionHandling = false;
            while(!exceptionHandling) // Loop will not end until exceptionHandling is set to true
                Console.Write("Enter an Integer: ");  // User is required to enter an integer
                string input = Console.ReadLine();   // input is taking as string
                try // Try block begins
                {   // One more thing a project can have only one try block and have multiple catch blocks
                    decimalValue = int.Parse(input); // Parsing integer from string
                    exceptionHandling = true; // if entered value is an integer then try will be executed and it will not go to catch block
                catch (Exception)
                    Console.WriteLine("Valid values(0-9): "); // Catch block is executed only when input value is invalid
                    exceptionHandling = false;
            Console.WriteLine("Entered Integer: " + decimalValue); //Integer value is printed on the screen

/////////////////////////////////////////////////////////////////////////// Ends ///////////////////////////////////////////////////////////////////////////////

No comments:

Post a Comment