Skip to content

Instantly share code, notes, and snippets.

@csdear
Created October 7, 2014 14:13
Show Gist options
  • Save csdear/937496cbb816a011a8c2 to your computer and use it in GitHub Desktop.
Save csdear/937496cbb816a011a8c2 to your computer and use it in GitHub Desktop.
Try / Catch Basic : A try block with a StreamReader statement that opens a data file called data.txt and writes a string from the file. Following the try block is a catch block that catches any exception that results from the try block.
// This will throw a 'System.IO.FileNotFoundException'
public class ProcessFile
{
public static void Main()
{
try
{
StreamReader sr = File.OpenText("data.txt");
Console.WriteLine("The first line of this file is {0}", sr.ReadLine());
sr.Close();
}
catch (Exception e)
{
Console.WriteLine("An error occurred: '{0}'", e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment