Transcript CHAPTER 7

Lecture Set 8
Validating Data and Handling Exceptions
Part B – Structured Exception Handling
Objectives




To understand how to us the Structured
Exception handling tools of Visual Basic
Describe the Exception hierarchy and name
two of its subclasses.
Describe the use of Try…Catch statements to
catch specific exceptions as well as all
exceptions.
Learn how to throw exceptions and how to
catch them and take appropriate steps to
prevent software failure
7/18/2015 10:31 AM
Objectives (continued)





Describe the use of the properties and methods
of an exception object.
Describe the use of Throw statements.
Describe the three types of data validation that
you’re most likely to perform on a user entry.
Describe two ways that you can use generic
validation methods in a method that validates all
of the user entries for a form.
Describe the use the Validating event and the
use of masked text boxes for data validation.
7/18/2015 10:31 AM
Structured Exception Handling


Run-time errors will cause a program to
terminate because of an exception being
thrown
Exceptions can be thrown for several reasons






Numeric overflow errors
Type conversion errors
Division by zero errors
Database errors of all sorts
Null reference exceptions
Create structured exception handlers to
prevent a program from terminating
7/18/2015 10:31 AM
The Exception Class Hierarchy
7/18/2015 10:31 AM
The Exception Hierarchy for Five Common
Exceptions (related to computation ONLY)
System namespace
Exception
FormatException
ArithmeticException
OverflowException
InvalidCastException
DivideByZeroException
Why are Unhandled Exceptions Bad?


In a nutshell – software that
fails for any reason is
unacceptable
Software has to be written to
accept any input from the user (or
from external events) and react
appropriately
7/18/2015 10:31 AM
The Dialog Box for an Unhandled Exception
7/18/2015 10:31 AM
The System.Exception Class


All exceptions are derived from the
System.Exception class
Properties



The Message property contains an
informational message
The Source property is a string containing the
name of the application causing the error
The StackTrace property returns a string
containing the error location
7/18/2015 10:31 AM
The Syntax for a Simple Try...Catch statement
Syntax
try
trystatements block
catch
catchstatements block
A Try...Catch statement
try
{
subtotal = ToDecimal(txtSubtotal.Text);
discountPercent = .2m;
discountAmount = subtotal * discountPercent;
invoiceTotal = subtotal - discountAmount;
}
catch
{ MessageBox.Show( "Please enter a valid number for the "
+ "Subtotal field.", "Entry Error");
}
7/18/2015 10:31 AM
The Dialog Box that’s Displayed if an Exception
Occurs
7/18/2015 10:31 AM
Try-Catch (Another example)
private void btnGetWord_Click(object sender, EventArgs e)
{
btnGetWord.Enabled = false;
failureCount = 0;
newWord = Dictionary.getWord();
try
{
lblLetterNumbers.Visible = true;
lblOkay.Visible = true;
lblLetterNumbers.Text = BuildNewWordTemplate(newWord.Length);
}
catch
{
. . .
} // end Try-Catch
ResetLetters();
} // end GetWord_Click
Note that the exception name you choose (ex in this case) is an instantiation of an
object of an exception type with properties (such as Message) and methods (such
as GetType) associated with it. So what does this code do?
7/18/2015 10:31 AM
The syntax for a Try...Catch statement that
accesses the exception
try
trystatements block
catch (exceptionclass exceptionName)
catchstatements block
7/18/2015 10:31 AM
Structured Exception Handlers (Syntax)
try
// Place executable statements that might throw
// (cause) an exception in this block.
catch
// This code runs if the statements in the Try
// block throw an exception.
finally
// This code always runs immediately before
// the Try block or Catch block exits.
7/18/2015 10:31 AM
Two Common Properties for all Exceptions
It is important to understand how this statement works
Property
Message
StackTrace
Description
Gets a message (a string) that briefly describes the
current exception.
Gets a string that lists the procedures that were
called before the exception occurred.
A common method for all exceptions
Method
GetType()
Description
Gets the type of the current exception.
The Dialog Box Displayed if an Exception Occurs (VB)
The Complete Syntax for the Try...Catch Statement
This form of try-catch includes the specification of exception types
try
trystatements block
catch (mostspecificexception exceptionName)
catchstatements block
[catch (nextmostspecificexception exceptionName)
...
catchstatements block]
[catch (leastspecificexception exceptionName)
catchstatements block]
[finally
finallystatements block]
What’s in a Try-Catch Statement?




The Try block contains the code that is
executed if the exception is raised (thrown)
The Catch block contains the code that
actually handles the exceptions
Note that if multiple procedures are called in
the Try block, the Catch block catches all
exceptions that are not handled by the called
procedures
Variables declared within a Try … Catch block
are local to that block
7/18/2015 10:31 AM
Execution Flow of a Structured Exception
Handler (VB example)
7/18/2015 10:31 AM
A Try...Catch that Catches Specific Exceptions
try
{
monthlyInvestment = Convert.ToDecimal(txtMonthlyInvestment.Text);
yearlyInterestRate = Convert.ToDecimal(txtInterestRate.Text);
years = Convert.ToInt32(txtYears.Text);
months = years * 12;
monthlyInterestRate = yearlyInterestRate / 12 / 100;
. . .
}
catch (ExceptionFormat ex)
MessageBox.Show(ex.Message + "\n\n" + ex.GetType().ToString()
+ "\n" + ex.StackTrace, "Data Entry Other Exception!!");
catch (Exception ex)
...
finally
// This code runs whether or not an exception occur
PerformCleanup();
Note that the exception name you choose (ex in this case) is an instantiation of an object
of an exception type with properties (such as Message) and methods (such as GetType)
associated with it. So what does this code do?
Notes on the Last Slide




Always catch code for the most specific
exceptions first. Why?
The Finally code block is executed whether
the exception occurs and is caught or not
The ToDecimal and ToInt32 methods (of the
Convert class) do not do any rounding and
can lead to FormatExceptions in certain cases
This is as opposed to CDec and CInt, the
intrinsic functions that do rounding (which
can lead to type conversion errors)
7/18/2015 10:31 AM
Throwing Exceptions
The syntax for throwing a new exception
throw new Exceptionclass ([message]);
The syntax for throwing an existing exception
throw ExceptionName;
7/18/2015 10:31 AM
A Function that Throws a FormatException
public decimal compute(decimal monthlyInterestRate,
int months)
{
if (monthlyInvestment <= 0)
throw new FormatException
("Monthly Investment must be greater than 0.");
if (monthlyInterestRate <= 0)
throw new FormatException
("Interest Rate must be greater than 0.");
.
.
.
} // end compute
7/18/2015 10:31 AM
Throwing Exceptions for Special Purposes
Code that throws an Exception for testing purposes
try
{
subtotal = Convert.ToDecimal(txtSubtotal.Text);
throw new OverflowException;
}
catch (Exception ex)
MessageBox.Show(ex.Message + “\n” + “\n”
& ex.GetType().ToString()+ “\n” + “\n”
& ex.StackTrace, "Exception");
Code that rethrows an exception
try
Convert.ToDecimal(txtSubtotal.Text);
catch (FormatException fe)
{
txtSubtotal.Select();
throw fe;
} // end try-catch
7/18/2015 10:31 AM
When to Throw an Exception
 When a procedure encounters a situation where it isn’t able to
complete its task
 When you want to generate an exception to test an exception
handler
 When you want to catch the exception, perform some processing,
and then throw the exception again
7/18/2015 10:31 AM
Code To Validate One Data Entry Item

What data validation do you need to perform?

Ensure that an entry has been made




Ensure that the entry is in the proper format
Ensure that the entry range is valid
Note use of the Select method for a Textbox



In other words ensure that the user has not
skipped over the item
Moves control back to the given Textbox
Where parameters are used, Select also helps the
user get things correct by showing what the
incorrect entry
See also, pp. 200-203 in text
7/18/2015 10:31 AM
Three Functions for Validating Textbox Entries

These functions are generic ONLY in the
sense that they will work on any Textbox
However, the functions that check for
Decimal ranges and formats are not generic
as to the types of the values whose ranges or
formats are to be checked

SO – beware – read the code on pp. 202-205

7/18/2015 10:31 AM
Validating Multiple Entries



This material concerns the writing of a
function to validate multiple (three in this
case) textbox entries on a single form.
You can take your choice – separate
validations for each box or one per form (or
worse, one long compound condition)
Read pp. 204-209 in text
7/18/2015 10:31 AM