Sample program: Try / Catch exceptions user defined exceptions derived from System.Exception

R

raylopez99

*/
Try / Catch exceptions user defined exceptions derived from
System.Exception

The example demo program below shows how you can create your own user
defined catch exceptions in a Try/Catch block.

I post this because all the net examples I saw simply stopped with
"System.Exception" and running a simple string error message, but none
showed how you can fix an error,
nor how you could derive a user defined class from catch
"System.Exception". So this program is for archival purposes.

The program shows how you can fix or change error values (if you know
what they are) and continue with the program without simply exiting-
below the bool value
'bozobool' is (arbitrarily) changed to "true" from a value of
"false". Of course in a real program you would test for something
first, then "throw", not simply force a "throw" as
per the below.

In addition, the demo shows how it is important to pass parameters
needed by the 'catch block' using the constructor function: compare
loops i=1 with the other loops, e.g.,
i=2,3,4 below. Basically loop 1 hardly works (the composite class
TestErrorCl [TEC] is hidden from the user), but it does compile and
has no run-time errors, though how you
can extract the hidden composite class TEC is a bit of a mystery--
probably using 'reflection'--some code guru like Pete or Jon can point
this out).

Also the demo program demonstrates how to group exceptions or nest
exceptions (for some reason this was not compiling early on, but I got
it to work eventually)

In particular, it shows that if you nest exceptions you don't
necessarily have to exit a loop-this was news to me. But you must put
your 'try' inside the loop, as shown below,
rather than outside it.

/*

/////////////////// 9/22/07 /////

/// <summary>

/// demonstrates how to use Try/Catch using User Defined catch
/// clauses derived from System.Exception

///</summary>

using System;
using System.Collections.Generic;
using System.Text;

namespace nestc001
{
class SampleA //sample class SampleA
{
public int iA;
public bool bozobool;
public SampleA ()
{
iA = 1;
bozobool = false;

// bozobool is the default bool for class SampleA
// the below program uses the "catch" block
// to change bozobool from false to true. This is of course
// bad programming ("catch" has too much overhead and is slow),but
// the purpose is to demonstrate a user-defined catch clause

}
}

class TestErrorCl
{
public int iT;
private int jTC;
public SampleA a1;

public TestErrorCl()
{
iT = 100;
a1 = new SampleA();
jTC = a1.iA;

}

public TestErrorCl(int i)
{
iT = i;
a1 = new SampleA();
jTC = a1.iA + 10;
}

public void Function01(int i)
{
iT = 44 + i; // 44 added just arbitrarily to change the
value of iT
jTC = (int) Math.Pow((double)a1.iA, 2.0);
Console.WriteLine("iT: {0}, for TestErrorClass (TEC)
object {1}", iT, this.GetHashCode());

}

public void SetBozoBool()
{
a1.bozobool = true; //public method to change bozobool to
true
}

internal void PrintHi()
{
Console.WriteLine("Hi, PrintHi function of TestErrorCl");
}
public int return_the_iT()
{
return iT;
}
}


class UserDefinedErrorClass : ArgumentException //manditory that
AE is the base
{
static int counti;
int ieye;
TestErrorCl caughtTECl;
public UserDefinedErrorClass()
{
Console.WriteLine("inside UDEC 'UserDefinedErrorClass()'
now");
ieye = 999;
counti = 0;
int sthis0i1 = this.GetHashCode();
Console.WriteLine("GetHashCode (1) of UDEC here is: {0}",
sthis0i1);
caughtTECl = new TestErrorCl(ieye);
Console.WriteLine ("caughtTEC1 has hash: {0}, and bozobool
(false?) = {1}", caughtTECl.GetHashCode(),caughtTECl.a1.bozobool);
caughtTECl.Function01(ieye);
HandleError();
caughtTECl.SetBozoBool();
Console.WriteLine("caughtTEC1 STILL has hash: {0}, and
bozobool (true?) = {1}", caughtTECl.GetHashCode(),
caughtTECl.a1.bozobool);
}
public UserDefinedErrorClass(int i, TestErrorCl Oh)
{
Console.WriteLine("inside 'UserDefinedErrorClass [UDEC]
(int i, TestErrorCl Oh)' now");
string sthis01 = this.GetHashCode().ToString();
Console.WriteLine("GetHashCode(2) here [for UDEC] is:
{0}", sthis01);
counti++;
if (i == 2) { ieye = 200; }
//if (i == 3) { ieye = 300; }
if (i == 4) { ieye = 400; }
//caughtTECl = Oh; //compiles, but bad form to redirect
objects needlessly
//caughtTECl.PrintHi();
Oh.PrintHi();
Oh.Function01(ieye);
HandleError(i);
Console.WriteLine("TestErrorCl Oh has hash: {0}, and
bozobool (false?) = {1}", Oh.GetHashCode(), Oh.a1.bozobool);

SetBozoBool_in_TestErrorCl(Oh);
Console.WriteLine("TestErrorCl Oh (still) has hash: {0},
and bozobool (true?) = {1}", Oh.GetHashCode(), Oh.a1.bozobool);


}

public void HandleError (int i)
{
Console.WriteLine("Now handling Error from inside
UserDefinedError cl, using i, ieye={0},{1}", i, ieye);
//caughtTEC1.Function01(i); // won't compile, as
caughtTEC1 is local

}

public void HandleError()
{
Console.WriteLine("HandleError() reached now, but it's not
as easy to use w/o parameter!");
//caughtTEC1. //won't compile, as local variable
}

private void SetBozoBool_in_TestErrorCl(TestErrorCl OhBozo)
{
OhBozo.SetBozoBool();
}

public int HashFunctionInt()
{
return this.GetHashCode();

}

}

class Tester01
{
TestErrorCl myTestEC_member;

public Tester01() //originally was a static class but I made
it non-static
{
myTestEC_member = new TestErrorCl();
//UserDefinedErrorClass myUDErrCl = new
UserDefinedErrorClass(); //not needed...I thought you needed to
instantiate your user defined catch but you don't.

}

public void TestIt()
//avoid 'static' qualifier here if myTestEC_member being used,
otherwise static OK
{

TestErrorCl localTEC = new TestErrorCl();
int pvloc0001 = localTEC.GetHashCode();
Console.WriteLine("Object TEC (localTEC) hash here is:
{0}", pvloc0001);
bool TestIeye = false;
if (TestIeye) throw new ArgumentException("OK,
thrown");

for (int i = 1; i <= 7; i++)
{
try
{

if (i == 1) throw new
UserDefinedErrorClass(); //ackward: no 'state' information passed--
compare with other loops below

if (i == 2) throw new UserDefinedErrorClass(i,
myTestEC_member);

if (i == 3)
{
TestErrorCl Inner_localTEC = new
TestErrorCl(333); //inner class TEC

Console.WriteLine("Inner_localTEC.GetHashCode() is: {0}",
Inner_localTEC.GetHashCode());
throw new UserDefinedErrorClass(i,
Inner_localTEC);
}

if (i == 4) throw new UserDefinedErrorClass(i,
localTEC);

if (i == 5) throw new Exception("Exception msg
string here...has no effect...not printed");

if (i == 6) throw new
ArgumentException("Exception msg string here...is printed)");

// program continues (here, one more loop), not terminated by
// ArgumentException automatically

if (i == 7) Console.WriteLine(" \n i==7 here!
loop is not abruptly terminated by throwing exceptions! \n");

}

catch (UserDefinedErrorClass ThrownUDEC)
{
int iHashCatch = ThrownUDEC.HashFunctionInt();
Console.WriteLine("!catch Hash int is: {0}",
iHashCatch);
Console.WriteLine("\n");
// ironically, in the actual "catch" block you don't do much, if at
all--all I do here is check and verify that the object UDEC ThrownUDEC
hash here is the same as the hash of the

object UDEC 'thrown', and indeed it is --all the work in fixing the
error is done in the 'throw' statement using the constructor of UDEC

}

catch (ArgumentException ex) //base class AE--most
books just show this
{
string myString = ex.Message;
Console.WriteLine("inside ArgumentException" +
myString);
Console.WriteLine(" ");
}

catch //primitive "Exception", shown in old books
{

Console.WriteLine("Grouping Exceptions: Does
this trigger? (i=5) Yes");
Console.WriteLine(" ");
}

}
try
{
// throw new Exception("Exception msg string here");
}
catch
{
Console.WriteLine("Does this trigger? No");
}

finally
{
Console.WriteLine("finally here"); //always triggered,
I don't know why but it's not important, you can comment out
}

}
}


}
//////////////////////////////////
// OUTPUT

Object TEC (localTEC) hash here is: 58225482 //[object used in loop
i=4 below]

inside UDEC 'UserDefinedErrorClass()' now
GetHashCode (1) of UDEC here is: 18643596
caughtTEC1 has hash: 33574638, and bozobool (false?) = False
iT: 1043, for TestErrorClass (TEC) object 33574638
HandleError() reached now, but it's not as easy to use w/o parameter!
caughtTEC1 STILL has hash: 33574638, and bozobool (true?) = True
!catch Hash int is: 18643596 //[NOTE: matches the hash of UDEC above,
as expected]


inside 'UserDefinedErrorClass [UDEC](int i, TestErrorCl Oh)' now
GetHashCode(2) here [for UDEC] is: 33736294
Hi, PrintHi function of TestErrorCl
iT: 244, for TestErrorClass (TEC) object 35191196
Now handling Error from inside UserDefinedError cl, using i,
ieye=2,200
TestErrorCl Oh has hash: 35191196, and bozobool (false?) = False
TestErrorCl Oh (still) has hash: 35191196, and bozobool (true?) = True
!catch Hash int is: 33736294


Inner_localTEC.GetHashCode() is: 48285313
inside 'UserDefinedErrorClass [UDEC](int i, TestErrorCl Oh)' now
GetHashCode(2) here [for UDEC] is: 31914638
Hi, PrintHi function of TestErrorCl
iT: 44, for TestErrorClass (TEC) object 48285313
Now handling Error from inside UserDefinedError cl, using i, ieye=3,0
TestErrorCl Oh has hash: 48285313, and bozobool (false?) = False
TestErrorCl Oh (still) has hash: 48285313, and bozobool (true?) = True
!catch Hash int is: 31914638


inside 'UserDefinedErrorClass [UDEC](int i, TestErrorCl Oh)' now
GetHashCode(2) here [for UDEC] is: 18796293
Hi, PrintHi function of TestErrorCl
iT: 444, for TestErrorClass (TEC) object 58225482
Now handling Error from inside UserDefinedError cl, using i,
ieye=4,400
TestErrorCl Oh has hash: 58225482, and bozobool (false?) = False
TestErrorCl Oh (still) has hash: 58225482, and bozobool (true?) = True
!catch Hash int is: 18796293


Grouping Exceptions: Does this trigger? (i=5) Yes

inside ArgumentExceptionException msg string here...is printed)


i==7 here! loop is not abruptly terminated by throwing exceptions!

finally here
Press any key to continue . . .
/////////////////////////////////
 
R

raylopez99

Just to complete the loop and dot all i's and cross all T's, you need
these two lines in main(), since the classes are not static:

Tester01 myTest = new Tester01();
myTest.TestIt();


RL
 
R

raylopez99

Also the demo program demonstrates how to group exceptions or nest
exceptions (for some reason this was not compiling early on, but I got
it to work eventually)

I also figured out this error: when grouping "catch" blocks, you must
group them properly, with the "derived" catch block [in this example
UserDefinedErrorClass] coming before the "base" catch block
[ArgumentException], or else the derived catch block will never be
seen by the program.

RL
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top