Csharp/C Sharp/Language Basics/Exception Try Catch
Содержание
- 1 An exception can be generated by one method and caught by another
- 2 Catch different exceptions
- 3 Catch Divide By Zero Exception
- 4 Catch Error
- 5 Catches an exception that was thrown in a component
- 6 Demonstrate exception handling
- 7 Demonstrates stacking catch blocks to provide alternate code for more than one exception type
- 8 Demonstrates using if statements to sort out an IOException
- 9 Exception Handling:Trying and Catching
- 10 Exception Type Mismatch
- 11 Handle error gracefully and continue
- 12 illustrates a nested try/catch block
- 13 illustrates an unhandled exception
- 14 illustrates exception propagation with methods
- 15 illustrates how to handle a specific exception
- 16 illustrates multiple catch blocks
- 17 Passing Exceptions on to the Caller: Caller Confuse
- 18 Passing Exceptions on to the Caller: Caller Inform
- 19 Several catch branches
- 20 Throw a format exception purposely to demonstrate catching a FormatException
- 21 Use a nested try block
- 22 Use multiple catch statements
- 23 Use the "catch all" catch statement
An exception can be generated by one method and caught by another
/*
C#: The Complete Reference
by Herbert Schildt
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
/* An exception can be generated by one
method and caught by another. */
using System;
class ExcTest {
// Generate an exception.
public static void genException() {
int[] nums = new int[4];
Console.WriteLine("Before exception is generated.");
// Generate an index out-of-bounds exception.
for(int i=0; i < 10; i++) {
nums[i] = i;
Console.WriteLine("nums[{0}]: {1}", i, nums[i]);
}
Console.WriteLine("this won"t be displayed");
}
}
public class ExcDemo2 {
public static void Main() {
try {
ExcTest.genException();
}
catch (IndexOutOfRangeException) {
// catch the exception
Console.WriteLine("Index out-of-bounds!");
}
Console.WriteLine("After catch statement.");
}
}
Catch different exceptions
/*
C# Programming Tips & Techniques
by Charles Wright, Kris Jamsa
Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/
namespace nsCompare
{
using System;
public class Compare
{
static public void Main (string [] args)
{
int TestArg;
try
{
TestArg = int.Parse (args[0]);
}
catch (FormatException)
{
Console.WriteLine ("Please enter a number value.");
return;
}
catch (IndexOutOfRangeException)
{
Console.WriteLine ("Please enter an argument");
return;
}
string str;
str = TestArg > 10 ? "The test is true" : "The test is false";
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);
}
}
}
Catch Error
using System;
public class CatchError
{
public static void Main()
{
int var1 = 1000, var2 = 0, var3;
try
{
var3 = var1 / var2;
}
catch (ArithmeticException e)
{
Console.WriteLine("Exception: {0}", e.ToString());
var3 = -1;
}
catch (Exception e)
{
Console.WriteLine("Exception: {0}", e.ToString());
var3 = -2;
}
Console.WriteLine("The result is: {0}", var3);
}
}
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);
}
}
}
Demonstrate exception handling
/*
C#: The Complete Reference
by Herbert Schildt
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Demonstrate exception handling.
using System;
public class ExcDemo1 {
public static void Main() {
int[] nums = new int[4];
try {
Console.WriteLine("Before exception is generated.");
// Generate an index out-of-bounds exception.
for(int i=0; i < 10; i++) {
nums[i] = i;
Console.WriteLine("nums[{0}]: {1}", i, nums[i]);
}
Console.WriteLine("this won"t be displayed");
}
catch (IndexOutOfRangeException) {
// catch the exception
Console.WriteLine("Index out-of-bounds!");
}
Console.WriteLine("After catch statement.");
}
}
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);
}
}
}
Demonstrates using if statements to sort out an IOException
/*
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);
}
}
}
}
Exception Handling:Trying and Catching
using System;
public class TryingCatching
{
static int Zero = 0;
public static void Main()
{
// watch for exceptions here
try
{
int j = 22 / Zero;
}
// exceptions that occur in try are transferred here
catch (Exception e)
{
Console.WriteLine("Exception " + e.Message);
}
Console.WriteLine("After catch");
}
}
Exception Type Mismatch
/*
C#: The Complete Reference
by Herbert Schildt
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// This won"t work!
using System;
public class ExcTypeMismatch {
public static void Main() {
int[] nums = new int[4];
try {
Console.WriteLine("Before exception is generated.");
// Generate an index out-of-bounds exception.
for(int i=0; i < 10; i++) {
nums[i] = i;
Console.WriteLine("nums[{0}]: {1}", i, nums[i]);
}
Console.WriteLine("this won"t be displayed");
}
/* Can"t catch an array boundary error with a
DivideByZeroException. */
catch (DivideByZeroException) {
// catch the exception
Console.WriteLine("Index out-of-bounds!");
}
Console.WriteLine("After catch statement.");
}
}
Handle error gracefully and continue
/*
C#: The Complete Reference
by Herbert Schildt
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Handle error gracefully and continue.
using System;
public class ExcDemo3 {
public static void Main() {
int[] numer = { 4, 8, 16, 32, 64, 128 };
int[] denom = { 2, 0, 4, 4, 0, 8 };
for(int i=0; i < numer.Length; i++) {
try {
Console.WriteLine(numer[i] + " / " +
denom[i] + " is " +
numer[i]/denom[i]);
}
catch (DivideByZeroException) {
// catch the exception
Console.WriteLine("Can"t divide by Zero!");
}
}
}
}
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);
}
}
}
illustrates an unhandled exception
/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy
Publisher: Sybex;
ISBN: 0782129110
*/
/*
Example13_7.cs illustrates an unhandled exception
*/
using System;
public class Example13_7
{
public static void Main()
{
int[] myArray = new int[2];
Console.WriteLine("Attempting to access an invalid array element");
myArray[2] = 1;
}
}
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 how to handle a specific exception
/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy
Publisher: Sybex;
ISBN: 0782129110
*/
/*
Example13_3.cs illustrates how to handle a specific exception
*/
using System;
public class Example13_3
{
public static void Main()
{
try
{
int zero = 0;
Console.WriteLine("In try block: attempting division by zero");
int myInt = 1 / zero; // throws the exception
}
catch (DivideByZeroException myException)
{
// code that handles a DivideByZeroException
Console.WriteLine("Message = " + myException.Message);
Console.WriteLine("StackTrace = " + myException.StackTrace);
}
}
}
illustrates multiple catch blocks
/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy
Publisher: Sybex;
ISBN: 0782129110
*/
/*
Example13_4.cs illustrates multiple catch blocks
*/
using System;
public class Example13_4
{
public static void Main()
{
try
{
int[] myArray = new int[2];
Console.WriteLine("Attempting to access an invalid array element");
myArray[2] = 1;
}
catch (DivideByZeroException e)
{
// code that handles a DivideByZeroException
Console.WriteLine("Handling a System.DivideByZeroException object");
Console.WriteLine("Message = " + e.Message);
Console.WriteLine("StackTrace = " + e.StackTrace);
}
catch (IndexOutOfRangeException e)
{
// code that handles an IndexOutOfRangeException
Console.WriteLine("Handling a System.IndexOutOfRangeException object");
Console.WriteLine("Message = " + e.Message);
Console.WriteLine("StackTrace = " + e.StackTrace);
}
catch (Exception e)
{
// code that handles a generic Exception: all other exceptions
Console.WriteLine("Handling a System.Exception object");
Console.WriteLine("Message = " + e.Message);
Console.WriteLine("StackTrace = " + e.StackTrace);
}
}
}
Passing Exceptions on to the Caller: Caller Confuse
/*
A Programmer"s Introduction to C# (Second Edition)
by Eric Gunnerson
Publisher: Apress L.P.
ISBN: 1-893115-62-3
*/
// 04 - Exception Handling\Passing Exceptions on to the Caller\Caller Confuse
// copyright 2000 Eric Gunnerson
using System;
public class CallerConfuse
{
public static void Main()
{
Summer summer = new Summer();
try
{
summer.DoAverage();
}
catch (Exception e)
{
Console.WriteLine("Exception {0}", e);
}
}
}
public class Summer
{
int sum = 0;
int count = 0;
float average;
public void DoAverage()
{
try
{
average = sum / count;
}
catch (DivideByZeroException e)
{
// do some cleanup here
throw;
}
}
}
Passing Exceptions on to the Caller: Caller Inform
/*
A Programmer"s Introduction to C# (Second Edition)
by Eric Gunnerson
Publisher: Apress L.P.
ISBN: 1-893115-62-3
*/
// 04 - Exception Handling\Passing Exceptions on to the Caller\Caller Inform
// copyright 2000 Eric Gunnerson
using System;
public class CallerInform
{
public static void Main()
{
Summer summer = new Summer();
try
{
summer.DoAverage();
}
catch (Exception e)
{
Console.WriteLine("Exception: {0}", e);
}
}
}
public class Summer
{
int sum = 0;
int count = 0;
float average;
public void DoAverage()
{
try
{
average = sum / count;
}
catch (DivideByZeroException e)
{
// wrap exception in another one,
// adding additional context.
throw (new DivideByZeroException(
"Count is zero in DoAverage()", e));
}
}
}
Several catch branches
/*
Learning C#
by Jesse Liberty
Publisher: O"Reilly
ISBN: 0596003765
*/
using System;
namespace ExceptionHandling
{
public class TesterExceptionHandling4
{
public void Run()
{
try
{
double a = 5;
double b = 0;
Console.WriteLine("Dividing {0} by {1}...",a,b);
Console.WriteLine ("{0} / {1} = {2}",
a, b, DoDivide(a,b));
}
// most derived exception type first
catch (System.DivideByZeroException)
{
Console.WriteLine(
"DivideByZeroException caught!");
}
catch (System.ArithmeticException)
{
Console.WriteLine(
"ArithmeticException caught!");
}
// generic exception type last
catch
{
Console.WriteLine(
"Unknown exception caught");
}
}
// 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...");
TesterExceptionHandling4 t = new TesterExceptionHandling4();
t.Run();
Console.WriteLine("Exit Main...");
}
}
}
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);
}
}
}
}
Use a nested try block
/*
C#: The Complete Reference
by Herbert Schildt
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Use a nested try block.
using System;
public class NestTrys {
public static void Main() {
// Here, numer is longer than denom.
int[] numer = { 4, 8, 16, 32, 64, 128, 256, 512 };
int[] denom = { 2, 0, 4, 4, 0, 8 };
try { // outer try
for(int i=0; i < numer.Length; i++) {
try { // nested try
Console.WriteLine(numer[i] + " / " +
denom[i] + " is " +
numer[i]/denom[i]);
}
catch (DivideByZeroException) {
// catch the exception
Console.WriteLine("Can"t divide by Zero!");
}
}
}
catch (IndexOutOfRangeException) {
// catch the exception
Console.WriteLine("No matching element found.");
Console.WriteLine("Fatal error -- program terminated.");
}
}
}
Use multiple catch statements
/*
C#: The Complete Reference
by Herbert Schildt
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Use multiple catch statements.
using System;
public class ExcDemo4 {
public static void Main() {
// Here, numer is longer than denom.
int[] numer = { 4, 8, 16, 32, 64, 128, 256, 512 };
int[] denom = { 2, 0, 4, 4, 0, 8 };
for(int i=0; i < numer.Length; i++) {
try {
Console.WriteLine(numer[i] + " / " +
denom[i] + " is " +
numer[i]/denom[i]);
}
catch (DivideByZeroException) {
// catch the exception
Console.WriteLine("Can"t divide by Zero!");
}
catch (IndexOutOfRangeException) {
// catch the exception
Console.WriteLine("No matching element found.");
}
}
}
}
Use the "catch all" catch statement
/*
C#: The Complete Reference
by Herbert Schildt
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Use the "catch all" catch statement.
using System;
public class ExcDemo5 {
public static void Main() {
// Here, numer is longer than denom.
int[] numer = { 4, 8, 16, 32, 64, 128, 256, 512 };
int[] denom = { 2, 0, 4, 4, 0, 8 };
for(int i=0; i < numer.Length; i++) {
try {
Console.WriteLine(numer[i] + " / " +
denom[i] + " is " +
numer[i]/denom[i]);
}
catch {
Console.WriteLine("Some exception occurred.");
}
}
}
}