CSCI E-143 CertPrep: Error Handling
(Kalani, chapter 3)
Saturday, Oct. 23, 2004
This Saturday we will cover Kalani's chapter 3,
"Error Handling for the User Interface".
Here are some things in Kalani that you should know about:
Exceptions
- The Exception, ApplicationException,
and SystemException classes:
- What's the difference?
- Which derive from which?
- Which should you use?
- You should be familiar with all six members Kalani lists
(on page 233) for the
Exception class:
- HelpLink is a URL
- InnerException is the exception
"above" this one in the chain of throws
- Message is your description of the problem
- Source is the application
- StackTrace is the method-calling chain
- TargetSite is the method where
the exception arose
- You should be familiar with the way .NET handles odd results
of floating-point operations.
See the box on page 234 of Kalani,
and also at the bottom of this web page.
- try and catch:
- The order of specification of catch blocks:
- Specific to general
- There's a catch (sorry): this ordering applies to catch-blocks
specified at the same level of a program
- What happens if you specify the catch blocks
in the wrong order?
- What happens if you don't specify a matching
catch block at all?
- Whether you need a catch block at all,
and why you would write a try block without a
following catch
- Exceptions which are not CLS-compliant (Kalani, box, page 237)
- They don't derive from System.Exception
(distinguish System.Exception from
SystemException)
- You catch them with a catch block
that doesn't specify an exception
- You can't do much if you don't specify any exception type
in the catch block
- You get them by running unmanaged code.
The checked and
unchecked operators
- See Kalani, page 238, box, for the rules
- checked vs.
unchecked, of course, but also
- compile time vs. run time
- See the C# Language Specification, section 7.5.12,
for details, such as when you would use
unchecked
to avoid problems with constants during compilation
- Yes, you might get a question about this
The throw statement
- It's expensive; you only use it for unusual situations,
not for normal program flow
- Re-throwing an existing exception
- You don't need to specify the exception in the
throw statement if you want to
re-throw the exception just caught
- In fact, you don't need to specify the exception in the
catch statement at all,
but this is less useful. This works:
try {}
catch
{throw;}
but it won't give you any specifics about the exception just caught.
Throwing a new exception
- The throw statement is not
restricted to use within catch
blocks
- You can wrap the exception just caught within the new exception by using
the InnerException parameter
- This may create a chain of wrapped exceptions
When the finally block is done.
You will get a question about this, and it's not hard
to remember the rules.
- It's always donethat's the point
- There must not be any extraneous code between
try,
catch, and
finally blocks
The using() statement and its relation to
the finally statement:
Kalani mentions using()
only on the last line of page 242.
Some information extracted from the C# Language Specification
is reproduced at the bottom of this web page.
Custom Exceptions
- Derive from
System.ApplicationException
- Give a name ending with Exception
- Implement three constructors:
- one with no parameters
- one with a message parameter
- one with both a message and an inner exception parameter
Managing unhandled exceptions
- What is an AppDomain?
- Our Mr. Holley will have a lot to say about this later
- For the purposes of CertPrep, you need to know that
the AppDomain
is part of the environmental hierarcy your routine runs in,
and that environmental settings and events may be effected at the
AppDomain level.
- When is an exception not an exception?
When it's an event. Specifically, the
AppDomain
raises an UnhandledException event
if no exception handler catches an exception.
This event has two arguments:
- ExceptionObject
(Information about the exception)
- IsTerminating
(The action of the CLR)
- For the way to handle such an event, see the example
starting on page 252. Specifically, you
- create an AppDomain
object in your routine, and
- attach an
UnhandledExceptionEventHandler to it
- You might use this event handler to log such an event.
Of the logging facilities, the Windows Event Log is
the most robust, but it's newit's not available on
Windows systems up through Windows 98.
Validating user input
- Keystroke-level validation
- The three events that occur as a character is typed:
KeyDown, KeyPress, KeyUp
- KeyPressEventArgs vs.
KeyEventArgs
- The KeyPreview property of a form:
- if set to true, the form
receives all keystroke events
- if the Handled property for
the event arg is set to true
the active control does not receive the key event
- Field-level validation. You want to do this when you think
what the user finished entering data into a fieldspecifically,
- Field-level validation is done when control passes out of a field.
- Validation: the exact order of events when entering and leaving a control.
There is a list of such events on Kalani's page 258:
Enter, GotFocus, Leave, Validating, Validated,
LostFocus. This list is not long.
Memorize it.
- The Validating event
- Use this to notify the user of problems.
- You can use the Focus()
to set focus on this (or any other) field
- Setting the Cancel property
of the CancelEventArgs argument
to true cancels the
validating event, and leaves focus on the control.
This may cause a form to refuse to close.
(Kalani, page 259, box)
- The CausesValidation property
- Set it to false
if you don't want a mouse press on this field to cause validation
in other fields
- A perfect example of such a field that must not cause validation
is a "Help" button:
if it caused validation, you might never get to the help
information.
- ErrorProvider
- It provides pop-up message like those of ToolTips if there is a
problem with the data in the field
- Like ToolTips, you have to add an
ErrorProvider control to the form
before you can add error providers to individual controls on the form
- You may want to enable or disable controls depending on the data present
in other controls
- Distinguish Enabled = false
from Readonly
- Two properties used by the TextBox control:
- CharacterCasing.
Done as the user types.
- MaxLength.
This controls only the user's input,
not what you can set into the field through code.
This looks like a lot of detail, but I think it's a lot easier to handle
than an equivalent length of stuff in chapter 2 was.
You remember chapter 2?
See you Saturday.
Floating-point operations
(from the C# Language Specifications, section 4.1.5)
The floating-point operators, including the assignment operators,
never produce exceptions.
Instead, in exceptional situations,
floating-point operations produce zero, infinity, or NaN,
as described below:
- If the result of a floating-point operation is too small for the destination
format, the result of the operation becomes positive zero
or negative zero.
- If the result of a floating-point operation is too large for the destination
format, the result of the operation becomes positive infinity
or negative infinity.
- If a floating-point operation is invalid, the result of the
operation becomes NaN.
- If one or both operands of a floating-point operation is NaN,
the result of the operation becomes NaN.
The using statement
(as opposed to the using directive)
(from the C# Language Specifications, section 8.13)
[In the following example, "R"
is a "Resource",] a class or struct
that implements System.IDisposable,
which includes a single parameterless method named
Dispose....
...a using statement of the form
using (R r1 = new R(), r2 = new R())
{
r1.F();
r2.F();
}
is precisely equivalent to:
using (R r1 = new R())
using (R r2 = new R())
{
r1.F();
r2.F();
}
which is, by expansion, precisely equivalent to:
R r1 = new R();
try
{
R r2 = new R();
try
{
r1.F();
r2.F();
}
finally
{
if (r2 != null) ((IDisposable)r2).Dispose();
}
}
finally
{
if (r1 != null) ((IDisposable)r1).Dispose();
}
Here are the relevant questions from the two tests at the end
of the "short Kalani" book:
Test 1: questions
19 (page 364; answer: page 392),
23, 34.
Test 2: question
11 (page 408; answer: page 441).
(Some of these questions may duplicate those in long Kalani.
Both texts are listed
here.)
Last revised Oct. 23, 2004