Csharp/C Sharp/Language Basics/Exception Finally — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
Admin (обсуждение | вклад) м (1 версия) |
(нет различий)
|
Текущая версия на 11:39, 26 мая 2010
Содержание
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\r\n");
}
try
{
SmallProblem ();
}
catch (clsException e)
{
Console.WriteLine (e.Message);
}
finally
{
Console.WriteLine ("But not big enough to exit\r\n");
}
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;
}
}
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(
"\nDivideByZeroException! Msg: {0}",
e.Message);
Console.WriteLine(
"\nHelpLink: {0}", e.HelpLink);
Console.WriteLine(
"\nHere"s a stack trace: {0}\n",
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.ru";
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 Handling Finally
/*
A Programmer"s Introduction to C# (Second Edition)
by Eric Gunnerson
Publisher: Apress L.P.
ISBN: 1-893115-62-3
*/
// 04 - Exception Handling\Finally
// 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();
}
}
}
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...");
}
}
}
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");
}
}
}
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();
}
}
}
Use final to deal with custom Exceptions
using System;
using System.Runtime.Serialization;
class TestDirectoryMissingException : ApplicationException {
public TestDirectoryMissingException() :
base() {
}
public TestDirectoryMissingException(string msg) :
base(msg) {
}
public TestDirectoryMissingException(SerializationInfo info, StreamingContext cxt) :
base(info, cxt) {
}
public TestDirectoryMissingException(string msg, Exception inner) :
base(msg, inner) {
}
}
class MainClass {
static void DoStuff() {
if (System.IO.Directory.Exists("c:\\test") == false)
throw new TestDirectoryMissingException("The test directory does not exist");
}
static void Main(string[] args) {
try {
DoStuff();
} catch (System.IO.DirectoryNotFoundException e1) {
System.Console.WriteLine(e1.StackTrace);
System.Console.WriteLine(e1.Source);
System.Console.WriteLine(e1.TargetSite);
} catch (System.IO.FileNotFoundException e2) {
} catch (System.Exception e) {
System.Console.WriteLine("Ex");
} finally {
System.Console.WriteLine("final");
}
}
}