using System; class ThrowException2App { class CommaDelimitedFile { protected string fileName; public void Open(string fileName) { this.fileName = fileName; // Attempt to open file // and throw exception upon error condition. throw new Exception("open failed"); } public bool Read(string record) { // Code to read file. return false; // EOF } } public static void Main() { try { Console.WriteLine("attempting to open file"); CommaDelimitedFile file = new CommaDelimitedFile(); file.Open("c:\\test.csv"); string record = ""; Console.WriteLine("reading from file"); while (file.Read(record) == true) { Console.WriteLine(record); } Console.WriteLine("finished reading file"); } catch (Exception e) { Console.WriteLine(e.Message); } } }
In this example, if either the CommaDelimitedFile.Open method or the CommaDelimitedFile.Read method throws an exception, the calling method is forced to deal with it. If the calling method does not catch the exception and no other method in the current code path attempts to catch an exception of this type, the application will abort. Pay particular attention to the fact that because the Open method call is placed in a block, an invalid read (using our example in which the Open method has thrown an exception) would not be attempted. This is because programmatic control would be passed from the Open call in the try block to the first line of the catch block. Therefore, one of the biggest benefits of exception handling over return codes is that exceptions are programmatically more difficult to ignore.