Mega Code Archive

 
Categories / C# / Language Basics
 

Demonstrates stacking catch blocks to provide alternate code for more than one exception type

/* C# Programming Tips & Techniques by Charles Wright, Kris Jamsa Publisher: Osborne/McGraw-Hill (December 28, 2001) ISBN: 0072193794 */ // Except.cs -- Demonstrates stacking catch blocks to provide alternate code for // more than one exception type. // // Compile this program with the following command line: //    C:>csc Except.cs // namespace nsExcept {     using System;     using System.IO;          public class Except     {         static public void Main (string [] args)         {             if (args.Length == 0)             {                 Console.WriteLine ("Please enter a file name");                 return;             }             try             {                 ReadFile (args[0]);             }             catch (ArgumentException)             {                 Console.WriteLine ("The file name " + args [0] +                           " is empty or contains an invalid character");             }             catch (FileNotFoundException)             {                 Console.WriteLine ("The file name " + args [0] +                                    " cannot be found");             }             catch (DirectoryNotFoundException)             {                 Console.WriteLine ("The path for " + args [0] +                                    " is invalid");             }             catch (Exception e)             {                 Console.WriteLine (e);             }         }         static public void ReadFile (string FileName)         {             FileStream strm = new FileStream (FileName, FileMode.Open,                                                         FileAccess.Read);             StreamReader reader = new StreamReader (strm);             string str = reader.ReadToEnd ();             Console.WriteLine (str);         }     } }