using System; using System.Reflection; public class Starter { public static bool bException = true; public static void Main() { try { MethodA(); } catch (Exception except) { Console.WriteLine(except.Message); bException = false; except.TargetSite.Invoke(null, null); } } public static void MethodA() { if (bException) { throw new ApplicationException("exception message"); } } }
Author: coder
calls GetBaseException and outputs the error message of the initial exception.
using System; public class Starter { public static void Main() { try { MethodA(); } catch (Exception except) { Exception original = except.GetBaseException(); Console.WriteLine(original.Message); } } public static void MethodA() { try { MethodB(); } catch (Exception except) { throw new ApplicationException("Inner Exception", except); } } public static void MethodB() { throw new ApplicationException("Innermost Exception"); } }
Derived exceptions must appear before base class exceptions
/*
C#: The Complete Reference
by Herbert Schildt
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Derived exceptions must appear before base class exceptions.
using System;
// Create an exception.
class ExceptA : ApplicationException {
public ExceptA() : base() { }
public ExceptA(string str) : base(str) { }
public override string ToString() {
return Message;
}
}
// Create an exception derived from ExceptA
class ExceptB : ExceptA {
public ExceptB() : base() { }
public ExceptB(string str) : base(str) { }
public override string ToString() {
return Message;
}
}
public class OrderMatters {
public static void Main() {
for(int x = 0; x < 3; x++) {
try {
if(x==0) throw new ExceptA("Caught an ExceptA exception");
else if(x==1) throw new ExceptB("Caught an ExceptB exception");
else throw new Exception();
}
catch (ExceptB exc) {
// catch the exception
Console.WriteLine(exc);
}
catch (ExceptA exc) {
// catch the exception
Console.WriteLine(exc);
}
catch (Exception exc) {
Console.WriteLine(exc);
}
}
}
}
[/csharp]
Use a custom Exception for RangeArray errors
/*
C#: The Complete Reference
by Herbert Schildt
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Use a custom Exception for RangeArray errors.
using System;
// Create an RangeArray exception.
class RangeArrayException : ApplicationException {
// Implement the standard constructors
public RangeArrayException() : base() { }
public RangeArrayException(string str) : base(str) { }
// Override ToString for RangeArrayException.
public override string ToString() {
return Message;
}
}
// An improved version of RangeArray.
class RangeArray {
// private data
int[] a; // reference to underlying array
int lowerBound; // lowest index
int upperBound; // greatest index
int len; // underlying var for Length property
// Construct array given its size.
public RangeArray(int low, int high) {
high++;
if(high <= low) {
throw new RangeArrayException("Low index not less than high.");
}
a = new int[high - low];
len = high - low;
lowerBound = low;
upperBound = --high;
}
// Read-only Length property.
public int Length {
get {
return len;
}
}
// This is the indexer for RangeArray.
public int this[int index] {
// This is the get accessor.
get {
if(ok(index)) {
return a[index - lowerBound];
} else {
throw new RangeArrayException("Range Error.");
}
}
// This is the set accessor.
set {
if(ok(index)) {
a[index - lowerBound] = value;
}
else throw new RangeArrayException("Range Error.");
}
}
// Return true if index is within bounds.
private bool ok(int index) {
if(index >= lowerBound & index <= upperBound) return true;
return false;
}
}
// Demonstrate the index-range array.
public class RangeArrayDemo1 {
public static void Main() {
try {
RangeArray ra = new RangeArray(-5, 5);
RangeArray ra2 = new RangeArray(1, 10);
// Demonstrate ra
Console.WriteLine("Length of ra: " + ra.Length);
for(int i = -5; i <= 5; i++)
ra[i] = i;
Console.Write("Contents of ra: ");
for(int i = -5; i <= 5; i++)
Console.Write(ra[i] + " ");
Console.WriteLine("
");
// Demonstrate ra2
Console.WriteLine("Length of ra2: " + ra2.Length);
for(int i = 1; i <= 10; i++)
ra2[i] = i;
Console.Write("Contents of ra2: ");
for(int i = 1; i <= 10; i++)
Console.Write(ra2[i] + " ");
Console.WriteLine("
");
} catch (RangeArrayException exc) {
Console.WriteLine(exc);
}
// Now, demonstrate some errors.
Console.WriteLine("Now generate some range errors.");
// Use an invalid constructor.
try {
RangeArray ra3 = new RangeArray(100, -10); // Error
} catch (RangeArrayException exc) {
Console.WriteLine(exc);
}
// Use an invalid index.
try {
RangeArray ra3 = new RangeArray(-2, 2);
for(int i = -2; i <= 2; i++)
ra3[i] = i;
Console.Write("Contents of ra3: ");
for(int i = -2; i <= 10; i++) // generate range error
Console.Write(ra3[i] + " ");
} catch (RangeArrayException exc) {
Console.WriteLine(exc);
}
}
}
[/csharp]
Use the NullReferenceException
/* C#: The Complete Reference by Herbert Schildt Publisher: Osborne/McGraw-Hill (March 8, 2002) ISBN: 0072134852 */ // Use the NullReferenceException. using System; class X { int x; public X(int a) { x = a; } public int add(X o) { return x + o.x; } } // Demonstrate NullReferenceException. public class NREDemo { public static void Main() { X p = new X(10); X q = null; // q is explicitly assigned null int val; try { val = p.add(q); // this will lead to an exception } catch (NullReferenceException) { Console.WriteLine("NullReferenceException!"); Console.WriteLine("fixing... "); // now, fix it q = new X(9); val = p.add(q); } Console.WriteLine("val is {0}", val); } }
Using Exception members
/*
C#: The Complete Reference
by Herbert Schildt
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Using Exception members.
using System;
class ExcTest {
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 UseExcept {
public static void Main() {
try {
ExcTest.genException();
}
catch (IndexOutOfRangeException exc) {
// catch the exception
Console.WriteLine("Standard message is: ");
Console.WriteLine(exc); // calls ToString()
Console.WriteLine("Stack trace: " + exc.StackTrace);
Console.WriteLine("Message: " + exc.Message);
Console.WriteLine("TargetSite: " + exc.TargetSite);
}
Console.WriteLine("After catch statement.");
}
}
[/csharp]
illustrates the use of a System.Exception object
/* Mastering Visual C# .NET by Jason Price, Mike Gunderloy Publisher: Sybex; ISBN: 0782129110 */ /* Example13_2.cs illustrates the use of a System.Exception object */ using System; public class Example13_2 { 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 (System.Exception myException) { // display the exception object's properties Console.WriteLine("HelpLink = " + myException.HelpLink); Console.WriteLine("Message = " + myException.Message); Console.WriteLine("Source = " + myException.Source); Console.WriteLine("StackTrace = " + myException.StackTrace); Console.WriteLine("TargetSite = " + myException.TargetSite); } } }