/* C# Programming Tips & Techniques by Charles Wright, Kris Jamsa Publisher: Osborne/McGraw-Hill (December 28, 2001) ISBN: 0072193794 */ // EnvTrace.cs -- demonstrates printing the stack trace from the Environment // when an exception is not thrown. // // Compile this program with the following command line: // C:>csc /debug:full EnvTrace.cs using System; using System.Diagnostics; namespace nsExceptions { public class EnvTrace { static public void Main () { clsTest test = new clsTest(); test.TestStackTrace (); Console.WriteLine (" Program completed normally"); } } public class clsTest { public void TestStackTrace () { try { CauseTrouble(1.7); } catch (Exception e) { Console.WriteLine (e.StackTrace); } } void CauseTrouble (double val) { clsAnother nudder = new clsAnother (); nudder.MakeProblem ((int) val); } } class clsAnother { public void MakeProblem (int x) { Console.WriteLine (Environment.StackTrace); } } }
Exception Handling Finally
/* A Programmer's Introduction to C# (Second Edition) by Eric Gunnerson Publisher: Apress L.P. ISBN: 1-893115-62-3 */ // 04 - Exception HandlingFinally // copyright 2000 Eric Gunnerson using System; using System.IO; public class ExceptionHandlingFinally { public static void Main() { Processor processor = new Processor(); try { processor.ProcessFile(); } catch (Exception e) { Console.WriteLine("Exception: {0}", e); } } } class Processor { int count; int sum; public int average; void CalculateAverage(int countAdd, int sumAdd) { count += countAdd; sum += sumAdd; average = sum / count; } public void ProcessFile() { FileStream f = new FileStream("data.txt", FileMode.Open); try { StreamReader t = new StreamReader(f); string line; while ((line = t.ReadLine()) != null) { int count; int sum; count = Convert.ToInt32(line); line = t.ReadLine(); sum = Convert.ToInt32(line); CalculateAverage(count, sum); } } // always executed before function exit, even if an // exception was thrown in the try. finally { f.Close(); } } }
Use finally
/*
C#: The Complete Reference
by Herbert Schildt
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Use finally.
using System;
class UseFinally {
public static void genException(int what) {
int t;
int[] nums = new int[2];
Console.WriteLine(“Receiving ” + what);
try {
switch(what) {
case 0:
t = 10 / what; // generate div-by-zero error
break;
case 1:
nums[4] = 4; // generate array index error.
break;
case 2:
return; // return from try block
}
}
catch (DivideByZeroException) {
// catch the exception
Console.WriteLine(“Can't divide by Zero!”);
return; // return from catch
}
catch (IndexOutOfRangeException) {
// catch the exception
Console.WriteLine(“No matching element found.”);
}
finally {
Console.WriteLine(“Leaving try.”);
}
}
}
public class FinallyDemo {
public static void Main() {
for(int i=0; i < 3; i++) { UseFinally.genException(i); Console.WriteLine(); } } } [/csharp]
Exception handle with finally
/* Learning C# by Jesse Liberty Publisher: O'Reilly ISBN: 0596003765 */ using System; namespace ExceptionHandling { public class TesterExceptionHandling6 { public void Run() { try { Console.WriteLine("Open file here"); double a = 12; double b = 0; Console.WriteLine ("{0} / {1} = {2}", a, b, DoDivide(a,b)); Console.WriteLine ( "This line may or may not print"); } // most derived exception type first catch (System.DivideByZeroException e) { Console.WriteLine( " DivideByZeroException! Msg: {0}", e.Message); Console.WriteLine( " HelpLink: {0}", e.HelpLink); Console.WriteLine( " Here's a stack trace: {0} ", e.StackTrace); } catch { Console.WriteLine( "Unknown exception caught"); } finally { Console.WriteLine ( "Close file here."); } } // do the division if legal public double DoDivide(double a, double b) { if (b == 0) { DivideByZeroException e = new DivideByZeroException(); e.HelpLink = "http://www.libertyassociates.com"; throw e; } if (a == 0) throw new ArithmeticException(); return a/b; } static void Main() { Console.WriteLine("Enter Main..."); TesterExceptionHandling6 t = new TesterExceptionHandling6(); t.Run(); Console.WriteLine("Exit Main..."); } } }
Exception with finally
/* Learning C# by Jesse Liberty Publisher: O'Reilly ISBN: 0596003765 */ using System; namespace ExceptionHandling { public class TesterExceptionHandling5 { public void Run() { try { Console.WriteLine("Open file here"); double a = 5; double b = 0; Console.WriteLine ("{0} / {1} = {2}", a, b, DoDivide(a,b)); Console.WriteLine ( "This line may or may not print"); } // most derived exception type first catch (System.DivideByZeroException) { Console.WriteLine( "DivideByZeroException caught!"); } catch { Console.WriteLine("Unknown exception caught"); } finally { Console.WriteLine ("Close file here."); } } // do the division if legal public double DoDivide(double a, double b) { if (b == 0) throw new System.DivideByZeroException(); if (a == 0) throw new System.ArithmeticException(); return a/b; } static void Main() { Console.WriteLine("Enter Main..."); TesterExceptionHandling5 t = new TesterExceptionHandling5(); t.Run(); Console.WriteLine("Exit Main..."); } } }
Demonstates the possible uses of a finally block
/* C# Programming Tips & Techniques by Charles Wright, Kris Jamsa Publisher: Osborne/McGraw-Hill (December 28, 2001) ISBN: 0072193794 */ // Finally.cs -- Demonstates the possible uses of a finally block // // Compile this program with the following command line: // C:>csc Finally.cs // namespace nsFinally { using System; public class Finally { static public void Main () { try { NoProblem (); } // No exception possible here. Use finally without a catch finally { Console.WriteLine ("No problem at all "); } try { SmallProblem (); } catch (clsException e) { Console.WriteLine (e.Message); } finally { Console.WriteLine ("But not big enough to exit "); } try { BigProblem (); } catch (DivideByZeroException e) { Console.WriteLine (e.Message); } finally { Console.WriteLine ("But the finally block still executes."); } } static public void NoProblem() { } static public void SmallProblem () { clsException ex = new clsException(); ex.Message = "Small problem encountered"; throw (ex); } static public void BigProblem () { clsException ex = new clsException(); ex.Message = "Big trouble. Applicaion must end."; throw (ex); } } // Define a custom exception class just for a personalized message public class clsException : Exception { new public string Message = null; } }
illustrates a try, catch, and finally block
/* Mastering Visual C# .NET by Jason Price, Mike Gunderloy Publisher: Sybex; ISBN: 0782129110 */ /* Example13_1.cs illustrates a try, catch, and finally block */ using System; public class Example13_1 { public static void Main() { try { // code that throws an exception int zero = 0; Console.WriteLine("In try block: attempting division by zero"); int myInt = 1 / zero; // throws the exception Console.WriteLine("You never see this message!"); } catch { // code that handles the exception Console.WriteLine("In catch block: an exception was thrown"); } finally { // code that does any cleaning up Console.WriteLine("In finally block: do any cleaning up here"); } } }