jloga4
7/20/2017 - 2:14 AM

Example of how to use the try catch construct to catch an exception. From Fundamentals of Computer Programming with C# http://www.introprogr

Example of how to use the try catch construct to catch an exception. From Fundamentals of Computer Programming with C# http://www.introprogramming.info/wp-content/uploads/2013/07/Books/CSharpEn/Fundamentals-of-Computer-Programming-with-CSharp-Nakov-eBook-v2013.pdf

static void Main()
{
  string fileName = "WrongTextFile.txt";
  ReadFile(fileName);
}

static void ReadFile(string fileName)
{
  // Exceptions could be thrown in the code below
  try 
  {
    TextReader reader = new StreamReader(fileName);
    string line = reader.ReadLine();
    Console.WriteLine(line);
    reader.Close();
  }
  catch (FileNotFoundException fnfe)
  {
    // Exception handler for FileNotFoundException
    // We just inform the user that there is no such file
    Console.WriteLine(
      "The file '{0}' is not found.", fileName);
  }
  catch (IOException ioe) 
  {
    // Exception handler for other input/output exceptions
    // We just print the stack trace on the console
    Console.WriteLine(ioe.StackTrace);
  }