/* C# Programming Tips & Techniques by Charles Wright, Kris Jamsa Publisher: Osborne/McGraw-Hill (December 28, 2001) ISBN: 0072193794 */ // IOExcept.cs -- Demonstrates using if statements to sort out an IOException // // Compile this program with the following command line: // C:>csc IOExcept.cs // namespace nsExcept { using System; using System.IO; public class IOExcept { static public void Main (string [] args) { if (args.Length == 0) { Console.WriteLine ("Please enter a file name"); return; } ReadFile (args[0]); } static public void ReadFile (string FileName) { FileStream strm = null; StreamReader reader = null; try { strm = new FileStream (FileName, FileMode.Open, FileAccess.Read); reader = new StreamReader (strm); while (reader.Peek() > 0) { string str = reader.ReadLine(); Console.WriteLine (str); } } catch (IOException e) { if (e is EndOfStreamException) { Console.WriteLine ("Attempted to read beyond end of file"); } else if (e is FileNotFoundException) { Console.WriteLine ("The file name " + FileName + " cannot be found"); return; } else if (e is DirectoryNotFoundException) { Console.WriteLine ("The path for name " + FileName + " cannot be found"); return; } else if (e is FileLoadException) { Console.WriteLine ("Cannot read from " + FileName); } reader.Close(); strm.Close (); } catch (Exception e) { Console.WriteLine (e.Message); } } } }
Language Basics
Throw a format exception purposely to demonstrate catching a FormatException
/* C# Programming Tips & Techniques by Charles Wright, Kris Jamsa Publisher: Osborne/McGraw-Hill (December 28, 2001) ISBN: 0072193794 */ // // FormExce.cs -- This program will throw a format exception purposeely // to demonstrate catching a FormatException. // // Compile this program with the following command line: // C:>csc FormExcep.cs // namespace nsExceptions { using System; public class FormExce { static public void Main () { const double pi = 3.14159; try { Console.WriteLine ("pi = {0,0:f5", pi); } catch (FormatException e) { Console.WriteLine (e.Message); } } } }
Catches an exception that was thrown in a component
/* C# Programming Tips & Techniques by Charles Wright, Kris Jamsa Publisher: Osborne/McGraw-Hill (December 28, 2001) ISBN: 0072193794 */ // FileOpen.cs -- Catches an exception that was thrown in a component // // Compile this program with the following command line: // C:>csc /r:fopen.dll FileOpen.cs // namespace nsFileOpen { using System; using System.IO; class clsMain { static public void Main () { clsFile file; try { file = new clsFile (""); } catch (Exception e) { Console.WriteLine (e.Message); Console.WriteLine ("Exception handled in client"); } } } } // Fopen.cs -- program to show exception handling in a component // // Compile this program with the following command line: // C:>csc /t:library Fopen.cs // namespace nsFileOpen { using System; using System.IO; public class clsFile { FileStream strm; public clsFile (string FileName) { strm = new FileStream (FileName, FileMode.Open, FileAccess.Read); } } }
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); } } }
Catch Divide By Zero Exception
/* C# Programming Tips & Techniques by Charles Wright, Kris Jamsa Publisher: Osborne/McGraw-Hill (December 28, 2001) ISBN: 0072193794 */ namespace nsDivZero { using System; public class DivZero { static public void Main () { // Set an integer equal to 0 int IntVal1 = 0; // and another not equal to zero int IntVal2 = 57; try { Console.WriteLine ("{0} / {1} = {2}", IntVal2, IntVal1, IntResult (IntVal2, IntVal1) / IntResult (IntVal2, IntVal1)); } catch (DivideByZeroException e) { Console.WriteLine (e.Message); } // Set a double equal to 0 double dVal1 = 0.0; double dVal2 = 57.3; try { Console.WriteLine ("{0} / {1} = {2}", dVal2, dVal1, DoubleResult (dVal2, dVal1)); } catch (DivideByZeroException e) { Console.WriteLine (e.Message); } } static public int IntResult (int num, int denom) { return (num / denom); } static public double DoubleResult (double num, double denom) { return (num / denom); } } }
illustrates exception propagation with methods
/* Mastering Visual C# .NET by Jason Price, Mike Gunderloy Publisher: Sybex; ISBN: 0782129110 */ /* Example13_6.cs illustrates exception propagation with methods */ using System; // declare the ExceptionsTest class class ExceptionsTest { public void AccessInvalidArrayElement() { int[] myArray = new int[2]; try { Console.WriteLine("Attempting to access an invalid array element"); myArray[2] = 1; } catch (IndexOutOfRangeException e) { Console.WriteLine("Handling an IndexOutOfRangeException"); Console.WriteLine("Message = " + e.Message); Console.WriteLine("StackTrace = " + e.StackTrace); } } public void DivideByZero() { int zero = 0; Console.WriteLine("Attempting division by zero"); int myInt = 1 / zero; } } public class Example13_6 { public static void Main() { ExceptionsTest myExceptionsTest = new ExceptionsTest(); // call the AccessInvalidArrayElement() method, // this method handles the exception locally Console.WriteLine("Calling AccessInvalidArrayElement()"); myExceptionsTest.AccessInvalidArrayElement(); try { // call the DivideByZero() method, // this method doesn't handle the exception locally and // so it must be handled here Console.WriteLine("Calling DivideByZero()"); myExceptionsTest.DivideByZero(); } catch (DivideByZeroException e) { Console.WriteLine("Handling an IndexOutOfRangeException"); Console.WriteLine("Message = " + e.Message); Console.WriteLine("StackTrace = " + e.StackTrace); } } }
illustrates a nested try/catch block
/* Mastering Visual C# .NET by Jason Price, Mike Gunderloy Publisher: Sybex; ISBN: 0782129110 */ /* Example13_5.cs illustrates a nested try/catch block; the nested if throws an exception that is propagated to the outer exception */ using System; public class Example13_5 { public static void Main() { try { // a nested try and catch block try { int[] myArray = new int[2]; Console.WriteLine("Attempting to access an invalid array element"); myArray[2] = 1; // throws the exception } catch (DivideByZeroException e) { // code that handles a DivideByZeroException Console.WriteLine("Handling a DivideByZeroException"); Console.WriteLine("Message = " + e.Message); Console.WriteLine("StackTrace = " + e.StackTrace); } } catch (IndexOutOfRangeException e) { // code that handles an IndexOutOfRangeException Console.WriteLine("Handling an IndexOutOfRangeException"); Console.WriteLine("Message = " + e.Message); Console.WriteLine("StackTrace = " + e.StackTrace); } } }