Handling Exceptions
Often a program will fail to compile correctly because of bugs within the code. 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.
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 }