Introduction to Exception Handling

This blog topic will give an overview on how to handle exceptions in your C# programs. The main objectives of this discussion are:

  • Know about an exception
  • Start a routine with a try/catch block
  • Release resources in a final block

Exceptions

Exceptions are unpredicted errors that happen in your programs. It is advisable to detect and handle program errors in your programming. For instance, assessing user input, checking null objects, and to verify the values returned from methods are all examples of good error handling that you must do all the time.

But, there are times when you don’t know if an error could occur. This is generally unlikely, but could still happen and you need to deal with them when they do occur. This is when exception handling comes in picture.

The System.Exception class gives you various methods and to obtain information on what went wrong. For instance, theMessage property gives summary information about what the error was, the Stacktrace property gives information from the stack for where the problem occurred, and the ToString() method is to reveal a verbose depiction of all the exceptions.

To identify the exceptions that you might need to handle depends on the routine you’re coding. E.g., if the routine opened a file with theSystem.IO.File.OpenRead() method, it could give any of the following exceptions:

  • SecurityException
  • ArgumentException
  • ArgumentNullException
  • PathTooLongException
  • DirectoryNotFoundException
  • UnauthorizedAccessException
  • FileNotFoundException
  • NotSupportedException

It’s easy to find out what exceptions a method can raise by looking in the .NET Frameworks SDK Documentation.

Try/catch Blocks

When exceptions are thrown, you must be able to handle them. This is done by using a try/catch block. Code that could throw an exception is put in the try block and exception handling code goes in the catch block. Listing 1 shows how to implement a try/catchblock. Since an OpenRead() method could throw one of several exceptions, it is placed in the try block. If an exception is thrown, it will be found in the catch block. The code in Listing 1 will print message and inform that if an exception is raised.

N.B. The programs in this lesson cause exceptions on purpose. The exceptions that are generated intentionally to exemplify the theoretical part.

Listing 1. Using try/catch Blocks: tryCatchDemo.cs

using System;

using System.IO;

class tryCatchDemo

{

    static void Main(string[] args)

    {

        try

        {

            File.OpenRead(“NonExistentFile”);

        }

        catch(Exception ex)

        {

            Console.WriteLine(ex.ToString());

        }

    }

}

Although the code in Listing 1 has a single catch block, all exceptions will be seen their owing to the type is of the base exception type “Exception”. In exception handling, more specific exceptions can be seen before their more general parent exceptions. E.g., the following code shows how to place multiple catch blocks:

catch(FileNotFoundException fnfex)

        {

            Console.WriteLine(fnfex.ToString());

        }

        catch(Exception ex)

        {

            Console.WriteLine(ex.ToString());

        }

If the file doesn’t exist, a FileNotFoundException exception will be shown and seen by the first catch block. However, if aPathTooLongException exception is raised, the second catch part would catch the exception.

Exceptions that can’t be handled will bubble up the stack until a calling routine in the call chain handles them. If you forget to include try/catch blocks in a part of your code and there aren’t any try/catch blocks earlier in the call chain, your program will stop with a message describing the exception. To mention that would be cryptic and uncomfortable for your users.

Finally Blocks

An exception leaves your program in an inconsistent state by not releasing the resources or by performing some other types of cleanup. A catch block is a nice place to figure out what may have gone wrong and try to recover, however it can’t cover all scenarios. So at times you need to perform clean up actions whether or not your program succeeds. At this situation it’s good for using a final block.

Listing 2 illustrates the usefulness of a finally block. Remember a file stream must be closed when you finished it. In this case, the file stream is the resource that should be cleaned up. In Listing 2, outStream is opened successfully, which means the program has a handle to an open file resource. When trying to open the inStream, a FileNotFoundException exception is raised, and the control goes immediately to the catch block.

It’s possible to close the outStream in the catch block, but if the algorithm is done successfully without an exception, how to deal with it? On success, the file will never be closed. We have included a finally block in Listing 2, which will always be carried out. Irrespective 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.

Listing 2. Implement a finally Block: FinallyDemo.cs

using System;

using System.IO;

class FinallyDemo

{

    static void Main(string[] args)

    {

        FileStream outStream = null;

        FileStream inStream = null;

        try

        {

            outStream = File.OpenWrite(“DestinationFile.txt”);

            inStream = File.OpenRead(“BogusInputFile.txt”);

        }

        catch(Exception ex)

        {

            Console.WriteLine(ex.ToString());

        }

        finally

        {

            if (outStream != null)

            {

                outStream.Close();

                Console.WriteLine(“outStream closed.”);

            }

            if (inStream != null)

            {

                inStream.Close();

                Console.WriteLine(“inStream closed.”);

            }

        }

    }

}

A finally block is not needed and you might ask what happens if you just put code after the catch block. Under normal circumstances, if the exception is found out, all code following the catch will be executed. However, try/catch/finally is for exceptional circumstances and it is always to be prepared for the worst.

Summary

The present blog topic was an introduction to handling exceptions. So now you must know what an exception is. You can implement algorithms within try/catch blocks that manage exceptions. Moreover you know how to clean up resources by using a finally block whose code is always effected before leaving a method.

We conclude the discussion here. Let us know your opinion in the comments sections below. And feel free to refer Microsoft’s site to gather more information.

If you want to improve your skill in ASP.Net and excel yourself in ASP.NET training program; our institute, CRB Tech Solutions would be of great help and for you. Come and join us with our scientifically structured program for .Net.

Stay connected to CRB Tech for more technical optimization and other updates and information.

Don't be shellfish...Buffer this pageEmail this to someoneDigg thisShare on FacebookShare on Google+Share on LinkedInPrint this pageShare on RedditPin on PinterestShare on StumbleUponTweet about this on TwitterShare on Tumblr

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>