Chapter 10: Exception Handling
Exception Handling
Structures
A Structure can be thought of as a “record
definition” within a C# program
Combines multiple data types into an object
that can be manipulated
In C++, was the same as a class.
Many times a better approach than parallel
arrays (but probably not as good as a class)
Structures
struct oStates
{
String sAbbrev = "";
String sName = "";
String sBird = "“;
int nPopulation = 0;
}
oStates[] myStates = new oStates[50];
This set up allows us to reference all the information about a
state by reference the myStates array.
– myStates[index].sAbbrev for example
Structures and our Quiz Program
Something in between using a class for the
questions and a parallel array could be to
use a question structure and then instancing
an array (or list) of those questions.
Exception Handling
Try…Catch…Finally
Code that may create a problem is placed in the try
block
Code to deal with the problem (the exception
handler) is placed in catch blocks
– catch clause
Code to be executed whether an exception is thrown
or not is placed in the finally block
Try…Catch…Finally
Generic catch clause
– Omit argument list with the catch
– Any exception thrown is handled by executing
code within that catch block
Control is never returned into the try block
after an exception is thrown
Using a try…catch block can keep the
program from terminating abnormally
Example
try {
int zero = 0;
int val = 100 / zero;
val = val + 1;
}
catch (DivideByZeroException ex)
{
throw new DivideByZeroException("Please don't
try to divide by zero !!", ex);
}
Exception Class
[Link]. Exception Class & Description
1 [Link]
Handles I/O errors.
2 [Link]
Handles errors generated when a method refers to an array index
out of range.
3 [Link]
Handles errors generated when type is mismatched with the array
type.
4 [Link]
Handles errors generated from referencing a null object.
Exception Class
[Link]. Exception Class & Description
5 [Link]
Handles errors generated from dividing a dividend with zero.
6 [Link]
Handles errors generated during typecasting.
7 [Link]
Handles errors generated from insufficient free memory.
8 [Link]
Handles errors generated from stack overflow.