Handling Exceptions

From TRCCompSci - AQA Computer Science
Revision as of 19:59, 10 January 2017 by Admin (talk | contribs)
Jump to: navigation, search

Even if you program compiles successfully, errors can still be generated at runtime during the execution of the program. When this occurs, visual studio will present you with an Exception. Sometimes, the generation of these errors cannot feasibly be avoided and thus requires the use of Exception Handling.

Exception handling is done by using the following code to control what code to run in case the program encounters a specific exception

1 try
2    {
3       //code to attempt to execute (may result in error)
4    }
5    catch(Exception)
6    {
7       //what to do if the code fails 
8       //this defaults to 'throw;' which will cause your program to exit unexpectedly. 
9    }

The 'Exception' part of the code can be left as is, but will catch ALL exceptions encountered within that piece of code, this can be a bad thing if a genuine error occurs and it is generally a good idea to determine the type of exception that you are encountering, and placing a reference to that there.

Determining the type of exception

An example of an 'IndexOutOfRangeException' in visual studio

When an exception is unhandled, visual studio will present a dialogue box presenting you with the type of exception and some possible solutions. In this image, the Exception is System.IndexOutOfRangeException. To catch this exception you would use the code:

1    catch(IndexOutOfRangeException)
2    {
3       //code to execute
4    }

Examples of Exception Handling

Example One:

Below is an example of how exception handling can be used to detect the existence of Text Files, and if one exists, load the username from the file.

 1 class Program 
 2 {
 3     static void Main(string[] args)
 4     {
 5        try
 6           {
 7                using (StreamReader Load = new StreamReader("Program/Preferences.txt"))
 8                   {
 9                        //Try to read from preferences.txt
10                        Username = Load.ReadLine();
11                   }
12           }
13           catch(NullReferenceException) //Null reference exception occurs when the file cannot be found
14           {
15                using (StreamWriter Save = new StreamWriter("Program/Preferences.txt"))
16                   {
17                        //Preferences.txt does not exist, so create one
18                        Save.Write(Username);
19                   }
20           }
21     }
22 }