Mt. San Jacinto College Computer Information Systems
Minimize header.

CSIS 111B: Fundamentals of Computer Programming: Lessons

Lesson 12

Exception Handling

Objectives

By the end of this lesson you will be able to:

  • Understand what syntax errors are
  • What logic errors are
  • what exception errors are
  • Understand what exceptions are
  • Create a program which implements exception handling with try/catch
  • Create a program which implements exception handling with try/catch/finally

Understanding Exception Handling

There are at least three distinguishable types of errors in computer programming:

  • Syntax errors, also known as parsing errors are the most common errors you will encounter while learning a new programming language.

  • Logic errors, like when an algorithm returns a divide by zero error.

  • Exceptions, even if your statements and expressions are syntactically and logically correct, you program may still cause an error when it executes due to exceptions occuring, access to file resources is unavailable, network connection to resources is unavailable, etc. At this point your program will crash and become unusable - not an optimal experience for the users of your program. Fortunately by applying exception handling to the blocks of your code that are most susseptable to these errors you can prevent your program from crashing when encountering one of these exceptions.

The .NET Framework supports standard exception handling to raise and handle runtime errors. In this section, you’ll learn how to use the try, catch, and finally keywords to handle exceptions.

An exception is an error condition that occurs during the execution of a computer program. When this happens, the runtime creates an object to represent the error and “throws” it. Unless you “catch” the exception by writing proper exception-handling code, program execution will terminate — a.k.a. crash.

For example, if you attempt to divide an integer by zero, a DivideByZeroException exception will be thrown. In the .NET Framework, an exception is represented by using an object of the System.Exception class or one of its derived classes. There are predefined exception classes that represent many commonly occurring error situations, such as the DivideByZeroException mentioned earlier. If you are designing an application that needs to throw any application-specific exceptions, you should create a custom exception class that derives from the System.Exception class.

Table of Contents
Handling Exceptions With Try-Catch

To handle exceptions, place the code that throws the exceptions inside a try block and place the code that handles the exceptions inside a catch block.

The following example shows how to use a try-catch block to handle an exception. The exercise uses the File.OpenText method to open a disk file. This statement will execute just fine in the normal case, but if the file (or permission to read the file) is missing, then an exception will be thrown.

To create your own Visual Studio project which demonstrates this concept, do the following:

  1. Create a new Console Application project to the Lesson10 solution and name it HandlingExceptions.
  2. Right-click on the newly added HandlingExceptions project and choose Set as StatUp Project from the context menu that appears.
  3. Click anywhere in the Source code editor window and pres Ctrl + A on your keyboard to select all of the template code in your new project, and then press Delete.
  4. Type, or copy & paste, the following code into the Source code window for your HandlingExceptions project.
        using System;
        using System.IO;

        namespace HandlingExceptions
        {
            class Program
            {
                static void Main(string[] args)
                {
                    ExceptionTest();
                }

                private static void ExceptionTest()
                {
                    StreamReader sr = null;
                    try
                    {
                        sr = File.OpenText(@"c:\data.txt");
                        Console.WriteLine(sr.ReadToEnd());
                    }
                    catch (FileNotFoundException fnfe)
                    {
                        Console.WriteLine(fnfe.Message);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                }
            }
        }            
  1. Create a text file (“data.txt”) using Notepad or Visual Studio in the root of your computer's C: drive. It is acceptable to create the file at a different location, but if you do so, remember to modify the file location in the program. Type some text (anything you want) in the file and Save it.
  2. After you have added the text file to the root of your C: drive, press CTRL + F5 to run your HandlingExceptions project code without debugging. Your program should display the contents of the text file.
  3. Press a key to close the command window.
  4. Delete or rename the data.txt file and run the program again. This time, you’ll get a FileNotFoundException exception, and an appropriate message will be displayed in the output window.

To handle an exception, you enclose the statements that could cause the exception in a try block, then you add catch blocks to handle one or more exceptions. In this example, in addition to handling the more specific FileNotFoundException exception, we are also using a catch block with more generic exceptions to catch all other exceptions. The exception name for a catch block must be enclosed within parentheses. The statements that are executed when an exception is caught must be enclosed within curly braces.

Code execution stops when an exception occurs. The runtime searches for a catch statement that matches the type of exception. If the first catch block doesn’t catch the raised excep- tion, control moves to the next catch block, and so on. If the exception is not handled in the method, the runtime checks for the catch statement in the calling code and continues for the rest of the call stack.

Note: In the ExceptionTest method, it is incorrect to change the order of the two catch blocks. The more specific exceptions need to be listed before the generic exceptions, or else you’ll get compilation errors.

Note: This is your first time seeing the @ symbol used in a C# statement. When placed in front of a string like the one in our example, "c:/data.txt", the @ symbol indicates to the compiler to treat the string literally (exactly as written). This can be useful when a backslash character is typed inside of a string value. Normally the compiler sees the backslash character in a string as what is known as an escape character. In C# coding, escape characters are used to change the normal behavior of the compiler in order to handle characters in a string that would normally cause a compiler error. For example, say you wanted to have literal quotes in a string value, you can't type "this is a quote " symbol" because the compiler would think that the string value should end after the word quote instead of where it should end after the word symbol. To fix this problem you can use an escape sequence like this "this is a quote \" symbol". In this example the backslash character is telling the compiler to treat the " character after the word quote as a character that is part of the string value and not the end of the string value. Escape characters are commonly used for this purpose in most programming languages. However, the question arises as to how then do we convey to a compiler that we want it to include a backslash character in a string and not treat it as an escape sequence? The answer is we use two backslashes. Telling the compiler that the first backslash begins the escape sequence and the second backslash is the literal character we want to include in the string value. Using our example above, you would normally write the filepath string using the backslash escape sequence like this: "c:\\data.txt", to avoid this we can use the @ symbol instead. By putting the @ symbol before the string value we are telling the compiler to ignore any and all escape characters that it finds inside of our string value.

If you are interested in learning more about escape sequences used in C# coding view the table in this Character literals tutorial.

Table of Contents
Handling Divide By Zero Errors

As shown in the example above Exception Handling can be used to avoid IO errors like accessing files on a local hard disk drive or even a network located resource. In fact, exception handling can be used to avoid many possible situations where you the programmer would have no control, take user input for example. Many time users ignore or don't bother to read your on-screen instructions for how to input data into your prgoram correctly. Here again exception handling comes in handy.

In our next example we'll look at handling a common mathematical calculation error know as divide by zero.

Create your own Visual Studio project which demonstrates this concept, by doing the following:

  1. Open your Lesson10 solution in Visual Studio
  2. Add a new Console Application project to the Lesson1 solution and name it ArithmeticException.
  3. Right-click on the newly added HandlingExceptions project and choose Set as StatUp Project from the context menu that appears.
  4. Click anywhere in the Source code editor window and pres Ctrl + A on your keyboard to select all of the template code in your new project, and then press Delete.
  5. Type the following code into the Source code window for your ArithmeticException project.
        using System;

        namespace ExceptionHandling
        {
            class Program
            {
                public static void Main()
                {
                    int x = 10;
                    int y = 0;
                    Console.WriteLine(Divide(x, y));
                }

                public static int Divide(int x, int y)
                {
                    int results = 0;
                    try
                    {
                        results = x / y;
                    }
                    catch (ArithmeticException e)
                    {
                        Console.WriteLine(
                         "ArithmeticException Handler: {0}",
                         e.ToString());
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(
                         "Generic Exception Handler: {0}",
                         e.ToString());
                    }
                    return results;
                }
            }
        }            
  1. Press CTRL + F5 to run your ArithmeticException project code without debugging. Your program should display an arithmetic exception error.

Note: A try block must have at least a catch block or a finally block associated with it.

Table of Contents
Using Try-Catch-Finally

The finally block is used in association with the try block. The finally block is always executed regardless of whether an exception is thrown. The finally block is often used to write clean-up code.

When an exception occurs, it often means that some lines of code after the exception were not executed. This may leave your program in a dirty or unstable state. To prevent such situations, you can use the finally statement to guarantee that certain cleanup code is always executed. This may involve closing connections, releasing resources, or setting variables to their expected values. We'll look at the finally block in the following exercise.

Create your own Visual Studio project which demonstrates this concept, by doing the following:

  1. Open your Lesson10 solution in Visual Studio
  2. Add a new Console Application project to the Lesson10 solution and name it TryCatchFinally.
  3. Right-click on the newly added TryCatchFinally project and choose Set as StatUp Project from the context menu that appears.
  4. Click anywhere in the Source code editor window and pres Ctrl + A on your keyboard to select all of the template code in your new project, and then press Delete.
  5. Type, or copy & paste, the following code into the Source code window for your TryCatchFinally project.
        using System;
        using System.IO;

        namespace TryCatchFinally
        {
            class Program
            {
                static void Main(string[] args)
                {
                    TryCatchFinallyTest();
                }

                private static void TryCatchFinallyTest()
                {
                    StreamReader sr = null;
                    try
                    {
                        sr = File.OpenText("data.txt");
                        Console.WriteLine(sr.ReadToEnd());
                    }
                    catch (FileNotFoundException fnfe)
                    {
                        Console.WriteLine(fnfe.Message);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                    finally
                    {
                        if (sr != null)
                        {
                            sr.Close();
                        }
                    }
                }
            }
        }  
  1. Press CTRL + F5 to run your TryCatchFinally project code without debugging.

In this example, the program makes sure that the StreamReader object is closed and any resources are released when the operation completes. The code in the finally block is executed regardless of whether an exception is thrown.

Table of Contents

Summary

In this lesson you learned what syntax errors are, what logic errors are, what exception errors are, how to create a program which implements exception handling with try/catch, and how to create a program which implements exception handling with try/catch/finally.