Skip to content

Instantly share code, notes, and snippets.

@jjhamshaw
Created June 10, 2012 12:56
Show Gist options
  • Save jjhamshaw/2905417 to your computer and use it in GitHub Desktop.
Save jjhamshaw/2905417 to your computer and use it in GitHub Desktop.
exception handling example - reads a file and writes contents to the console
class ListFile
{
static void Main(string[] args)
{
var arg0 = args[0];
try
{
var counter = 0;
if (args.Length <= 0)
{
Console.WriteLine("Format: ListFile filename");
return;
}
var fileStream = new FileStream(arg0, FileMode.Open);
try
{
var streamReader = new StreamReader(fileStream);
string line;
while ((line = streamReader.ReadLine()) != null)
{
counter++;
Console.WriteLine("{0}: {1}", counter, line);
}
}
catch (Exception e)
{
Console.WriteLine("Exception during read/write: {0}\n", e);
}
finally
{
fileStream.Close();
}
}
catch (FileNotFoundException)
{
Console.WriteLine("ListFile could not find the file {0}", arg0);
}
catch(Exception e)
{
Console.WriteLine("Exception: {0}\n\n,", e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment