Exception handler in sdk

G

Guest

I would appreciate some help in understanding the simple C# example relating
to handling exceptions. This one relates to catching an error thrown by
dividing number by zero.

There are a few things I don't understand which I hope you can help me with:




'using System;

class ExceptionTestClass
{
public static void Main()
{
int x = 0;
try
{
int y = 100/x;
}
catch (ArithmeticException e)
{
Console.WriteLine("ArithmeticException Handler: {0}",
e.ToString());
}
catch (Exception e)
{
Console.WriteLine("Generic Exception Handler: {0}",
e.ToString());
}
}
}

1. Is this class 'ExceptionTestClass a 'test' class for demonstration
purposes...why is there is not a general Exception class one could call
rather than the author's test?

2. The variable 'ArithmeticException' and 'e' ...are these standard incoming
variables from the excpection class or the author's exception class?

3. Why does he have two 'catch' classes....does the second one check the
first one to see if there was an error....

4. What is the difference between the 'ArithmeticException Handler and the
'Generic Exception Handler'.


I realise these are proabably naive questions but I am just starting out.

Thanks
Jason
 
M

Manohar Kamath

Jason,

1. Looks like a test class -- for demo purposes. It is a general practice to
catch exceptions at the top-most level class -- say UI. However, te
intentions here might be different (catch an exception, so the UI does not
have to)

2. The format is catch (<exception class> var)

The var is there so you can use it..

catch (Exception e)
{
// Show what happened
MessageBox.Show(e.ToString());
}

If you don't plan to use the exception object, just don't declare it

catch (Exception)
{
// do something generic here
}

for #3 and #4 see below:



Exception is a base class for all exceptions -- other classes derive from
that. So, if you want to catch just about any exception, all you have to do
is:

catch (Exception e)

However, if you want to catch specific exceptions, you have to do it before
you catch the general, broader, exception.


So, let us say:

Exception <--- MyExp1 <-- MyExp2

Where <-- is the inheritance tree.

Then, your catch sequence should go from MyExp2 to Exception


catch (MyExp2 e1)
{
}

catch (MyExp1 e2)
{
}

catch (Exception e)
{
}

The catch (Exception e) is the "catch all"
 

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