SlideShare a Scribd company logo
1 of 40
Murach’s C#
2010, C7 © 2010, Mike Murach & Associates, Inc.Slide 1
Chapter 7
How to
handle exceptions
and validate data
Murach’s C#
2010, C7 © 2010, Mike Murach & Associates, Inc.Slide 2
Objectives
Applied
1. Given a form that uses text boxes to accept data from the user,
write code that catches any exceptions that might occur.
2. Given a form that uses text boxes to accept data and the
validation specifications for that data, write code that validates
the user entries.
3. Use dialog boxes as needed within your applications.
Murach’s C#
2010, C7 © 2010, Mike Murach & Associates, Inc.Slide 3
Objectives (continued)
Knowledge
1. Describe the Exception hierarchy and name two of its subclasses.
2. Describe the use of try-catch statements to catch specific
exceptions as well as all exceptions.
3. Describe the use of the properties and methods of an exception
object.
4. Describe the use of throw statements.
5. Describe the three types of data validation that you’re most likely
to perform on a user entry.
6. Describe two ways that you can use generic validation methods in
a method that validates all of the user entries for a form.
Murach’s C#
2010, C7 © 2010, Mike Murach & Associates, Inc.Slide 4
The dialog box for an unhandled exception
Murach’s C#
2010, C7 © 2010, Mike Murach & Associates, Inc.Slide 5
The Exception hierarchy for five common
exceptions
System namespace
Exception
DivideByZeroExceptionOverflowException
ArithmeticExceptionFormatException
Murach’s C#
2010, C7 © 2010, Mike Murach & Associates, Inc.Slide 6
Methods that might throw exceptions
Class Method Exception
Convert ToDecimal(string) FormatException
Convert ToInt32(string) FormatException
Decimal Parse(string) FormatException
DateTime Parse(string) FormatException
Murach’s C#
2010, C7 © 2010, Mike Murach & Associates, Inc.Slide 7
The syntax to display a dialog box with an OK
button
MessageBox.Show(text[, caption]);
A dialog box with an OK button
The statement that displays this dialog box
MessageBox.Show(
"Please enter a valid number for the Subtotal field.",
"Entry Error");
Murach’s C#
2010, C7 © 2010, Mike Murach & Associates, Inc.Slide 8
The syntax for a simple try-catch statement
try { statements }
catch { statements }
A try-catch statement
try
{
decimal subtotal = Convert.ToDecimal(txtSubtotal.Text);
decimal discountPercent = .2m;
decimal discountAmount = subtotal * discountPercent;
decimal invoiceTotal = subtotal - discountAmount;
}
catch
{
MessageBox.Show(
"Please enter a valid number for the Subtotal " +
"field.", "Entry Error");
}
Murach’s C#
2010, C7 © 2010, Mike Murach & Associates, Inc.Slide 9
The dialog box that’s displayed if an exception
occurs
Murach’s C#
2010, C7 © 2010, Mike Murach & Associates, Inc.Slide 10
The syntax for a try-catch statement that accesses
the exception
try { statements }
catch(ExceptionClass exceptionName) { statements }
Two common properties for all exceptions
Property Description
Message Gets a message that briefly describes the current
exception.
StackTrace Gets a string that lists the methods that were called
before the exception occurred.
A common method for all exceptions
Method Description
GetType() Gets the type of the current exception.
Murach’s C#
2010, C7 © 2010, Mike Murach & Associates, Inc.Slide 11
A try-catch statement that accesses the exception
try
{
decimal subtotal
= Convert.ToDecimal(txtSubtotal.Text);
}
catch(Exception ex)
{
MessageBox.Show(
ex.Message + "nn" +
ex.GetType().ToString() + "n" +
ex.StackTrace,
"Exception");
}
Murach’s C#
2010, C7 © 2010, Mike Murach & Associates, Inc.Slide 12
The dialog box that’s displayed if an
exception occurs
Murach’s C#
2010, C7 © 2010, Mike Murach & Associates, Inc.Slide 13
The complete syntax for the try-catch statement
try { statements }
catch(MostSpecificException [exceptionName]) { statements }...
[catch(NextMostSpecificException [exceptionName]) { statements }]...
[catch([LeastSpecificException [exceptionName]]) { statements }]
[finally { statements }]
Murach’s C#
2010, C7 © 2010, Mike Murach & Associates, Inc.Slide 14
A try-catch statement that catches two specific
exceptions
try
{
decimal monthlyInvestment =
Convert.ToDecimal(txtMonthlyInvestment.Text);
decimal yearlyInterestRate =
Convert.ToDecimal(txtInterestRate.Text);
int years = Convert.ToInt32(txtYears.Text);
}
catch(FormatException) // a specific exception
{
MessageBox.Show(
"A format exception has occurred. " +
"Please check all entries.", "Entry Error");
}
Murach’s C#
2010, C7 © 2010, Mike Murach & Associates, Inc.Slide 15
A try-catch statement that catches two specific
exceptions (continued)
catch(OverflowException) // another specific exception
{
MessageBox.Show(
"An overflow exception has occurred. " +
"Please enter smaller values.", "Entry Error");
}
catch(Exception ex) // all other exceptions
{
MessageBox.Show(ex.Message, ex.GetType().ToString());
}
finally // this code runs whether or not
// an exception occurs
{
PerformCleanup();
}
Murach’s C#
2010, C7 © 2010, Mike Murach & Associates, Inc.Slide 16
The syntax for throwing a new exception
throw new ExceptionClass([message]);
The syntax for throwing an existing exception
throw exceptionName;
When to throw an exception
• When a method 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.
Murach’s C#
2010, C7 © 2010, Mike Murach & Associates, Inc.Slide 17
A method that throws an exception when an
exceptional condition occurs
private decimal CalculateFutureValue(
decimal monthlyInvestment,
decimal interestRateMonthly, int months)
{
if (monthlyInvestment <= 0)
throw new Exception("Monthly Investment must " +
"be greater than 0.");
if (interestRateMonthly <= 0)
throw new Exception("Interest Rate must be " +
"greater than 0.");
.
.
}
Murach’s C#
2010, C7 © 2010, Mike Murach & Associates, Inc.Slide 18
Code that throws an exception for testing
purposes
try
{
decimal subtotal
= Convert.ToDecimal(txtSubtotal.Text);
throw new Exception("An unknown exception " +
"occurred.");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + "nn"
+ ex.GetType().ToString() + "n"
+ ex.StackTrace, "Exception");
}
Murach’s C#
2010, C7 © 2010, Mike Murach & Associates, Inc.Slide 19
Code that rethrows an exception
try
{
Convert.ToDecimal(txtSubtotal.Text);
}
catch (FormatException fe)
{
txtBox.Focus();
throw fe;
}
Murach’s C#
2010, C7 © 2010, Mike Murach & Associates, Inc.Slide 20
The code for the Future Value application with
exception handling
private void btnCalculate_Click(object sender,
System.EventArgs e)
{
try
{
decimal monthlyInvestment =
Convert.ToDecimal(txtMonthlyInvestment.Text);
decimal yearlyInterestRate =
Convert.ToDecimal(txtInterestRate.Text);
int years = Convert.ToInt32(txtYears.Text);
decimal monthlyInterestRate
= yearlyInterestRate / 12 / 100;
int months = years * 12;
decimal futureValue = this.CalculateFutureValue(
monthlyInvestment, monthlyInterestRate, months);
txtFutureValue.Text = futureValue.ToString("c");
txtMonthlyInvestment.Focus();
}
Murach’s C#
2010, C7 © 2010, Mike Murach & Associates, Inc.Slide 21
The code for the Future Value application with
exception handling (continued)
catch(FormatException)
{
MessageBox.Show(
"Invalid numeric format. " +
"Please check all entries.", "Entry Error");
}
catch(OverflowException)
{
MessageBox.Show(
"Overflow error. Please enter smaller values.",
"Entry Error");
}
catch(Exception ex)
{
MessageBox.Show(
ex.Message,
ex.GetType().ToString());
}
}
Murach’s C#
2010, C7 © 2010, Mike Murach & Associates, Inc.Slide 22
The code for the Future Value application with
exception handling (continued)
private decimal CalculateFutureValue(
decimal monthlyInvestment, decimal monthlyInterestRate,
int months)
{
decimal futureValue = 0m;
for (int i = 0; i < months; i++)
{
futureValue = (futureValue + monthlyInvestment)
* (1 + monthlyInterestRate);
}
return futureValue;
}
Murach’s C#
2010, C7 © 2010, Mike Murach & Associates, Inc.Slide 23
Code that checks that an entry has been made
if (txtMonthlyInvestment.Text == "")
{
MessageBox.Show("Monthly Investment is a required " +
"field.", Entry Error);
txtMonthlyInvestment.Focus();
}
Code that checks an entry for a valid decimal
format
try
{
Convert.ToDecimal(txtMonthlyInvestment.Text);
}
catch (FormatException)
{
MessageBox.Show(
"Monthly Investment must be a numeric value.",
"Entry Error");
txtMonthlyInvestment.Focus();
}
Murach’s C#
2010, C7 © 2010, Mike Murach & Associates, Inc.Slide 24
Code that checks an entry for a valid range
decimal monthlyInvestment
= Convert.ToDecimal(txtMonthlyInvestment.Text);
if (monthlyInvestment <= 0)
{
MessageBox.Show(
"Monthly Investment must be greater than 0.",
"Entry Error");
txtMonthlyInvestment.Focus();
}
else if (monthlyInvestment >= 1000)
{
MessageBox.Show(
"Monthly Investment must be less than 1,000.",
"Entry Error");
txtMonthlyInvestment.Focus();
}
Murach’s C#
2010, C7 © 2010, Mike Murach & Associates, Inc.Slide 25
A method that checks for a required field
public bool IsPresent(TextBox textBox, string name)
{
if (textBox.Text == "")
{
MessageBox.Show(name + " is a required field.",
"Entry Error");
textBox.Focus();
return false;
}
return true;
}
Murach’s C#
2010, C7 © 2010, Mike Murach & Associates, Inc.Slide 26
A method that checks for a valid numeric format
public bool IsDecimal(TextBox textBox, string name)
{
try
{
Convert.ToDecimal(textBox.Text);
return true;
}
catch(FormatException)
{
MessageBox.Show(name + " must be a decimal " +
"value.", "Entry Error");
textBox.Focus();
return false;
}
}
Murach’s C#
2010, C7 © 2010, Mike Murach & Associates, Inc.Slide 27
A method that checks for a valid numeric range
public bool IsWithinRange(TextBox textBox, string name,
decimal min, decimal max)
{
decimal number = Convert.ToDecimal(textBox.Text);
if (number < min || number > max)
{
MessageBox.Show(name + " must be between " +
min.ToString() + " and " + max.ToString() +
".", "Entry Error");
textBox.Focus();
return false;
}
return true;
}
Murach’s C#
2010, C7 © 2010, Mike Murach & Associates, Inc.Slide 28
Code that uses generic methods to check the
validity of one entry
if (IsPresent(txtMonthlyInvestment, "Monthly Investment") &&
IsDecimal(txtMonthlyInvestment, "Monthly Investment") &&
IsWithinRange(txtMonthlyInvestment,
"Monthly Investment", 1, 1000))
{
MessageBox.Show("Monthly Investment is valid.", "Test");
}
Murach’s C#
2010, C7 © 2010, Mike Murach & Associates, Inc.Slide 29
Code that uses a series of simple if statements to
validate multiple entries
public bool IsValidData()
{
// Validate the Monthly Investment text box
if (!IsPresent(txtMonthlyInvestment, "Monthly Investment"))
return false;
if (!IsDecimal(txtMonthlyInvestment, "Monthly Investment"))
return false;
if (!IsWithinRange(txtMonthlyInvestment,
"Monthly Investment", 1, 1000))
return false;
// Validate the Interest Rate text box
if (!IsPresent(txtInterestRate, "Interest Rate"))
return false;
if (!IsDecimal(txtInterestRate, "Interest Rate"))
return false;
if (!IsWithinRange(txtInterestRate, "Interest Rate", 1, 20))
return false;
return true;
}
Murach’s C#
2010, C7 © 2010, Mike Murach & Associates, Inc.Slide 30
Code that uses compound conditions in a single
return statement to validate multiple entries
public bool IsValidData()
{
return
// Validate the Monthly Investment text box
IsPresent(txtMonthlyInvestment, "Monthly Investment") &&
IsDecimal(txtMonthlyInvestment, "Monthly Investment") &&
IsWithinRange(txtMonthlyInvestment, "Monthly Investment",
1, 1000) &&
// Validate the Interest Rate text box
IsPresent(txtInterestRate, "Yearly Interest Rate") &&
IsDecimal(txtInterestRate, "Yearly Interest Rate") &&
IsWithinRange(txtInterestRate, "Yearly Interest Rate",
1, 20);
}
Murach’s C#
2010, C7 © 2010, Mike Murach & Associates, Inc.Slide 31
The Future Value form with a dialog box for
required fields
Murach’s C#
2010, C7 © 2010, Mike Murach & Associates, Inc.Slide 32
The dialog box for invalid decimals
The dialog box for invalid ranges
Murach’s C#
2010, C7 © 2010, Mike Murach & Associates, Inc.Slide 33
The dialog box for an unanticipated exception
Murach’s C#
2010, C7 © 2010, Mike Murach & Associates, Inc.Slide 34
The code for the Future Value application
private void btnCalculate_Click(object sender,
System.EventArgs e)
{
try
{
if (IsValidData())
{
decimal monthlyInvestment =
Convert.ToDecimal(txtMonthlyInvestment.Text);
decimal yearlyInterestRate =
Convert.ToDecimal(txtInterestRate.Text);
int years = Convert.ToInt32(txtYears.Text);
int months = years * 12;
decimal monthlyInterestRate =
yearlyInterestRate / 12 / 100;
decimal futureValue = CalculateFutureValue(
monthlyInvestment, monthlyInterestRate,
months);
txtFutureValue.Text = futureValue.ToString("c");
txtMonthlyInvestment.Focus(); }
}
Murach’s C#
2010, C7 © 2010, Mike Murach & Associates, Inc.Slide 35
The code for the Future Value application (cont.)
catch(Exception ex)
{
MessageBox.Show(ex.Message + "nn" +
ex.GetType().ToString() + "n" +
ex.StackTrace, "Exception");
}
}
public bool IsValidData()
{
return
IsPresent(
txtMonthlyInvestment, "Monthly Investment") &&
IsDecimal(
txtMonthlyInvestment, "Monthly Investment") &&
IsWithinRange(txtMonthlyInvestment,
"Monthly Investment", 1, 1000) &&
Murach’s C#
2010, C7 © 2010, Mike Murach & Associates, Inc.Slide 36
The code for the Future Value application (cont.)
IsPresent(txtInterestRate, "Yearly Interest Rate") &&
IsDecimal(txtInterestRate, "Yearly Interest Rate") &&
IsWithinRange(txtInterestRate,
"Yearly Interest Rate", 1, 20) &&
IsPresent(txtYears, "Number of Years") &&
IsInt32(txtYears, "Number of Years") &&
IsWithinRange(txtYears, "Number of Years", 1, 40);
}
public bool IsPresent(TextBox textBox, string name)
{
if (textBox.Text == "")
{
MessageBox.Show(name + " is a required field.",
"Entry Error");
textBox.Focus();
return false;
}
return true;
}
Murach’s C#
2010, C7 © 2010, Mike Murach & Associates, Inc.Slide 37
The code for the Future Value application (cont.)
public bool IsDecimal(TextBox textBox, string name)
{
try
{
Convert.ToDecimal(textBox.Text);
return true;
}
catch(FormatException)
{
MessageBox.Show(name + " must be a decimal value.",
"Entry Error");
textBox.Focus();
return false;
}
}
Murach’s C#
2010, C7 © 2010, Mike Murach & Associates, Inc.Slide 38
The code for the Future Value application (cont.)
public bool IsInt32(TextBox textBox, string name)
{
try
{
Convert.ToInt32(textBox.Text);
return true;
}
catch(FormatException)
{
MessageBox.Show(name + " must be an integer.",
"Entry Error");
textBox.Focus();
return false; }
}
Murach’s C#
2010, C7 © 2010, Mike Murach & Associates, Inc.Slide 39
The code for the Future Value application (cont.)
public bool IsWithinRange(TextBox textBox, string name,
decimal min, decimal max)
{
decimal number = Convert.ToDecimal(textBox.Text);
if (number < min || number > max)
{
MessageBox.Show(name + " must be between " +
min + " and " + max + ".",
"Entry Error");
textBox.Focus();
return false; }
return true;
}
Murach’s C#
2010, C7 © 2010, Mike Murach & Associates, Inc.Slide 40
The code for the Future Value application (cont.)
private decimal CalculateFutureValue(
decimal monthlyInvestment, decimal monthlyInterestRate,
int months)
{
decimal futureValue = 0m;
for (int i = 0; i < months; i++)
{
futureValue = (futureValue + monthlyInvestment)
* (1 + monthlyInterestRate);
}
return futureValue;
}

More Related Content

What's hot

C# Tutorial MSM_Murach chapter-25-slides
C# Tutorial MSM_Murach chapter-25-slidesC# Tutorial MSM_Murach chapter-25-slides
C# Tutorial MSM_Murach chapter-25-slidesSami Mut
 
C# Tutorial MSM_Murach chapter-16-slides
C# Tutorial MSM_Murach chapter-16-slidesC# Tutorial MSM_Murach chapter-16-slides
C# Tutorial MSM_Murach chapter-16-slidesSami Mut
 
C# Tutorial MSM_Murach chapter-18-slides
C# Tutorial MSM_Murach chapter-18-slidesC# Tutorial MSM_Murach chapter-18-slides
C# Tutorial MSM_Murach chapter-18-slidesSami Mut
 
C# Tutorial MSM_Murach chapter-19-slides
C# Tutorial MSM_Murach chapter-19-slidesC# Tutorial MSM_Murach chapter-19-slides
C# Tutorial MSM_Murach chapter-19-slidesSami Mut
 
C# Tutorial MSM_Murach chapter-20-slides
C# Tutorial MSM_Murach chapter-20-slidesC# Tutorial MSM_Murach chapter-20-slides
C# Tutorial MSM_Murach chapter-20-slidesSami Mut
 
C# Tutorial MSM_Murach chapter-09-slides
C# Tutorial MSM_Murach chapter-09-slidesC# Tutorial MSM_Murach chapter-09-slides
C# Tutorial MSM_Murach chapter-09-slidesSami Mut
 
C# Tutorial MSM_Murach chapter-23-slides
C# Tutorial MSM_Murach chapter-23-slidesC# Tutorial MSM_Murach chapter-23-slides
C# Tutorial MSM_Murach chapter-23-slidesSami Mut
 
C# Tutorial MSM_Murach chapter-02-slides
C# Tutorial MSM_Murach chapter-02-slidesC# Tutorial MSM_Murach chapter-02-slides
C# Tutorial MSM_Murach chapter-02-slidesSami Mut
 
C# Tutorial MSM_Murach chapter-08-slides
C# Tutorial MSM_Murach chapter-08-slidesC# Tutorial MSM_Murach chapter-08-slides
C# Tutorial MSM_Murach chapter-08-slidesSami Mut
 
C# Tutorial MSM_Murach chapter-10-slides
C# Tutorial MSM_Murach chapter-10-slidesC# Tutorial MSM_Murach chapter-10-slides
C# Tutorial MSM_Murach chapter-10-slidesSami Mut
 
C# Tutorial MSM_Murach chapter-03-slides
C# Tutorial MSM_Murach chapter-03-slidesC# Tutorial MSM_Murach chapter-03-slides
C# Tutorial MSM_Murach chapter-03-slidesSami Mut
 
C# Tutorial MSM_Murach chapter-22-slides
C# Tutorial MSM_Murach chapter-22-slidesC# Tutorial MSM_Murach chapter-22-slides
C# Tutorial MSM_Murach chapter-22-slidesSami Mut
 
C# Tutorial MSM_Murach chapter-01-slides
C# Tutorial MSM_Murach chapter-01-slidesC# Tutorial MSM_Murach chapter-01-slides
C# Tutorial MSM_Murach chapter-01-slidesSami Mut
 
C# Tutorial MSM_Murach chapter-04-slides
C# Tutorial MSM_Murach chapter-04-slidesC# Tutorial MSM_Murach chapter-04-slides
C# Tutorial MSM_Murach chapter-04-slidesSami Mut
 
C# Tutorial MSM_Murach chapter-21-slides
C# Tutorial MSM_Murach chapter-21-slidesC# Tutorial MSM_Murach chapter-21-slides
C# Tutorial MSM_Murach chapter-21-slidesSami Mut
 
C# Tutorial MSM_Murach chapter-17-slides
C# Tutorial MSM_Murach chapter-17-slidesC# Tutorial MSM_Murach chapter-17-slides
C# Tutorial MSM_Murach chapter-17-slidesSami Mut
 
Chapter 2 — Program and Graphical User Interface Design
Chapter 2 — Program and Graphical User Interface DesignChapter 2 — Program and Graphical User Interface Design
Chapter 2 — Program and Graphical User Interface Designfrancopw
 
Cookbook Oracle SOA Business Rules
Cookbook Oracle SOA Business RulesCookbook Oracle SOA Business Rules
Cookbook Oracle SOA Business RulesEmiel Paasschens
 

What's hot (20)

C# Tutorial MSM_Murach chapter-25-slides
C# Tutorial MSM_Murach chapter-25-slidesC# Tutorial MSM_Murach chapter-25-slides
C# Tutorial MSM_Murach chapter-25-slides
 
C# Tutorial MSM_Murach chapter-16-slides
C# Tutorial MSM_Murach chapter-16-slidesC# Tutorial MSM_Murach chapter-16-slides
C# Tutorial MSM_Murach chapter-16-slides
 
C# Tutorial MSM_Murach chapter-18-slides
C# Tutorial MSM_Murach chapter-18-slidesC# Tutorial MSM_Murach chapter-18-slides
C# Tutorial MSM_Murach chapter-18-slides
 
C# Tutorial MSM_Murach chapter-19-slides
C# Tutorial MSM_Murach chapter-19-slidesC# Tutorial MSM_Murach chapter-19-slides
C# Tutorial MSM_Murach chapter-19-slides
 
C# Tutorial MSM_Murach chapter-20-slides
C# Tutorial MSM_Murach chapter-20-slidesC# Tutorial MSM_Murach chapter-20-slides
C# Tutorial MSM_Murach chapter-20-slides
 
C# Tutorial MSM_Murach chapter-09-slides
C# Tutorial MSM_Murach chapter-09-slidesC# Tutorial MSM_Murach chapter-09-slides
C# Tutorial MSM_Murach chapter-09-slides
 
C# Tutorial MSM_Murach chapter-23-slides
C# Tutorial MSM_Murach chapter-23-slidesC# Tutorial MSM_Murach chapter-23-slides
C# Tutorial MSM_Murach chapter-23-slides
 
C# Tutorial MSM_Murach chapter-02-slides
C# Tutorial MSM_Murach chapter-02-slidesC# Tutorial MSM_Murach chapter-02-slides
C# Tutorial MSM_Murach chapter-02-slides
 
C# Tutorial MSM_Murach chapter-08-slides
C# Tutorial MSM_Murach chapter-08-slidesC# Tutorial MSM_Murach chapter-08-slides
C# Tutorial MSM_Murach chapter-08-slides
 
C# Tutorial MSM_Murach chapter-10-slides
C# Tutorial MSM_Murach chapter-10-slidesC# Tutorial MSM_Murach chapter-10-slides
C# Tutorial MSM_Murach chapter-10-slides
 
C# Tutorial MSM_Murach chapter-03-slides
C# Tutorial MSM_Murach chapter-03-slidesC# Tutorial MSM_Murach chapter-03-slides
C# Tutorial MSM_Murach chapter-03-slides
 
C# Tutorial MSM_Murach chapter-22-slides
C# Tutorial MSM_Murach chapter-22-slidesC# Tutorial MSM_Murach chapter-22-slides
C# Tutorial MSM_Murach chapter-22-slides
 
C# Tutorial MSM_Murach chapter-01-slides
C# Tutorial MSM_Murach chapter-01-slidesC# Tutorial MSM_Murach chapter-01-slides
C# Tutorial MSM_Murach chapter-01-slides
 
C# Tutorial MSM_Murach chapter-04-slides
C# Tutorial MSM_Murach chapter-04-slidesC# Tutorial MSM_Murach chapter-04-slides
C# Tutorial MSM_Murach chapter-04-slides
 
C# Tutorial MSM_Murach chapter-21-slides
C# Tutorial MSM_Murach chapter-21-slidesC# Tutorial MSM_Murach chapter-21-slides
C# Tutorial MSM_Murach chapter-21-slides
 
C# Tutorial MSM_Murach chapter-17-slides
C# Tutorial MSM_Murach chapter-17-slidesC# Tutorial MSM_Murach chapter-17-slides
C# Tutorial MSM_Murach chapter-17-slides
 
Intake 38 9
Intake 38 9Intake 38 9
Intake 38 9
 
Intake 38 8
Intake 38 8Intake 38 8
Intake 38 8
 
Chapter 2 — Program and Graphical User Interface Design
Chapter 2 — Program and Graphical User Interface DesignChapter 2 — Program and Graphical User Interface Design
Chapter 2 — Program and Graphical User Interface Design
 
Cookbook Oracle SOA Business Rules
Cookbook Oracle SOA Business RulesCookbook Oracle SOA Business Rules
Cookbook Oracle SOA Business Rules
 

Similar to C# Tutorial MSM_Murach chapter-07-slides

2011 nri-pratiques tests-avancees
2011 nri-pratiques tests-avancees2011 nri-pratiques tests-avancees
2011 nri-pratiques tests-avanceesNathaniel Richand
 
Javascript_JQUERY_Desiging_Modules_User_interface_working_managing_html_codes...
Javascript_JQUERY_Desiging_Modules_User_interface_working_managing_html_codes...Javascript_JQUERY_Desiging_Modules_User_interface_working_managing_html_codes...
Javascript_JQUERY_Desiging_Modules_User_interface_working_managing_html_codes...pavithraven95
 
Bis 311 final examination answers
Bis 311 final examination answersBis 311 final examination answers
Bis 311 final examination answersRandalHoffman
 
Java 例外處理壞味道與重構技術
Java 例外處理壞味道與重構技術Java 例外處理壞味道與重構技術
Java 例外處理壞味道與重構技術teddysoft
 
Analysis of Microsoft Code Contracts
Analysis of Microsoft Code ContractsAnalysis of Microsoft Code Contracts
Analysis of Microsoft Code ContractsPVS-Studio
 
Mid term sem 2 1415 sol
Mid term sem 2 1415 solMid term sem 2 1415 sol
Mid term sem 2 1415 solIIUM
 
Lab 10 sem ii_12_13
Lab 10 sem ii_12_13Lab 10 sem ii_12_13
Lab 10 sem ii_12_13alish sha
 
31b - JUnit and Mockito.pdf
31b - JUnit and Mockito.pdf31b - JUnit and Mockito.pdf
31b - JUnit and Mockito.pdfgauravavam
 
Strategy Design Pattern
Strategy Design PatternStrategy Design Pattern
Strategy Design PatternGanesh Kolhe
 
Oops lab manual2
Oops lab manual2Oops lab manual2
Oops lab manual2Mouna Guru
 
MSc COMPUTER APPLICATION
MSc COMPUTER APPLICATIONMSc COMPUTER APPLICATION
MSc COMPUTER APPLICATIONMugdhaSharma11
 
"Используем MetricKit в бою" / Марина Звягина (Vivid Money)
"Используем MetricKit в бою" / Марина Звягина (Vivid Money)"Используем MetricKit в бою" / Марина Звягина (Vivid Money)
"Используем MetricKit в бою" / Марина Звягина (Vivid Money)Egor Petrov
 
Story of static code analyzer development
Story of static code analyzer developmentStory of static code analyzer development
Story of static code analyzer developmentAndrey Karpov
 
IRJET- Implementation and Unittests of AWS, Google Storage (Cloud) and Am...
IRJET-  	  Implementation and Unittests of AWS, Google Storage (Cloud) and Am...IRJET-  	  Implementation and Unittests of AWS, Google Storage (Cloud) and Am...
IRJET- Implementation and Unittests of AWS, Google Storage (Cloud) and Am...IRJET Journal
 

Similar to C# Tutorial MSM_Murach chapter-07-slides (20)

Rhino Mocks
Rhino MocksRhino Mocks
Rhino Mocks
 
2011 nri-pratiques tests-avancees
2011 nri-pratiques tests-avancees2011 nri-pratiques tests-avancees
2011 nri-pratiques tests-avancees
 
Good code
Good codeGood code
Good code
 
Javascript_JQUERY_Desiging_Modules_User_interface_working_managing_html_codes...
Javascript_JQUERY_Desiging_Modules_User_interface_working_managing_html_codes...Javascript_JQUERY_Desiging_Modules_User_interface_working_managing_html_codes...
Javascript_JQUERY_Desiging_Modules_User_interface_working_managing_html_codes...
 
Bis 311 final examination answers
Bis 311 final examination answersBis 311 final examination answers
Bis 311 final examination answers
 
Java 例外處理壞味道與重構技術
Java 例外處理壞味道與重構技術Java 例外處理壞味道與重構技術
Java 例外處理壞味道與重構技術
 
Analysis of Microsoft Code Contracts
Analysis of Microsoft Code ContractsAnalysis of Microsoft Code Contracts
Analysis of Microsoft Code Contracts
 
XP through TDD
XP through TDDXP through TDD
XP through TDD
 
Mid term sem 2 1415 sol
Mid term sem 2 1415 solMid term sem 2 1415 sol
Mid term sem 2 1415 sol
 
Lab 10 sem ii_12_13
Lab 10 sem ii_12_13Lab 10 sem ii_12_13
Lab 10 sem ii_12_13
 
31b - JUnit and Mockito.pdf
31b - JUnit and Mockito.pdf31b - JUnit and Mockito.pdf
31b - JUnit and Mockito.pdf
 
Strategy Design Pattern
Strategy Design PatternStrategy Design Pattern
Strategy Design Pattern
 
Oops lab manual2
Oops lab manual2Oops lab manual2
Oops lab manual2
 
Digital Design Session 9
Digital Design Session 9Digital Design Session 9
Digital Design Session 9
 
MSc COMPUTER APPLICATION
MSc COMPUTER APPLICATIONMSc COMPUTER APPLICATION
MSc COMPUTER APPLICATION
 
"Используем MetricKit в бою" / Марина Звягина (Vivid Money)
"Используем MetricKit в бою" / Марина Звягина (Vivid Money)"Используем MetricKit в бою" / Марина Звягина (Vivid Money)
"Используем MetricKit в бою" / Марина Звягина (Vivid Money)
 
Story of static code analyzer development
Story of static code analyzer developmentStory of static code analyzer development
Story of static code analyzer development
 
Programming in Life
Programming in LifeProgramming in Life
Programming in Life
 
Express 070 536
Express 070 536Express 070 536
Express 070 536
 
IRJET- Implementation and Unittests of AWS, Google Storage (Cloud) and Am...
IRJET-  	  Implementation and Unittests of AWS, Google Storage (Cloud) and Am...IRJET-  	  Implementation and Unittests of AWS, Google Storage (Cloud) and Am...
IRJET- Implementation and Unittests of AWS, Google Storage (Cloud) and Am...
 

More from Sami Mut

chapter 5 Java at rupp cambodia
chapter 5 Java at rupp cambodiachapter 5 Java at rupp cambodia
chapter 5 Java at rupp cambodiaSami Mut
 
chapter 2 Java at rupp cambodia
chapter 2 Java at rupp cambodiachapter 2 Java at rupp cambodia
chapter 2 Java at rupp cambodiaSami Mut
 
chapter 3 Java at rupp cambodia
chapter 3 Java at rupp cambodiachapter 3 Java at rupp cambodia
chapter 3 Java at rupp cambodiaSami Mut
 
chapter 2 Java at rupp cambodia
chapter 2 Java at rupp cambodiachapter 2 Java at rupp cambodia
chapter 2 Java at rupp cambodiaSami Mut
 
chapter 1 Java at rupp cambodia
chapter 1 Java at rupp cambodiachapter 1 Java at rupp cambodia
chapter 1 Java at rupp cambodiaSami Mut
 

More from Sami Mut (6)

MSM_Time
MSM_TimeMSM_Time
MSM_Time
 
chapter 5 Java at rupp cambodia
chapter 5 Java at rupp cambodiachapter 5 Java at rupp cambodia
chapter 5 Java at rupp cambodia
 
chapter 2 Java at rupp cambodia
chapter 2 Java at rupp cambodiachapter 2 Java at rupp cambodia
chapter 2 Java at rupp cambodia
 
chapter 3 Java at rupp cambodia
chapter 3 Java at rupp cambodiachapter 3 Java at rupp cambodia
chapter 3 Java at rupp cambodia
 
chapter 2 Java at rupp cambodia
chapter 2 Java at rupp cambodiachapter 2 Java at rupp cambodia
chapter 2 Java at rupp cambodia
 
chapter 1 Java at rupp cambodia
chapter 1 Java at rupp cambodiachapter 1 Java at rupp cambodia
chapter 1 Java at rupp cambodia
 

Recently uploaded

#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Neo4j
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxnull - The Open Security Community
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 

Recently uploaded (20)

#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 

C# Tutorial MSM_Murach chapter-07-slides

  • 1. Murach’s C# 2010, C7 © 2010, Mike Murach & Associates, Inc.Slide 1 Chapter 7 How to handle exceptions and validate data
  • 2. Murach’s C# 2010, C7 © 2010, Mike Murach & Associates, Inc.Slide 2 Objectives Applied 1. Given a form that uses text boxes to accept data from the user, write code that catches any exceptions that might occur. 2. Given a form that uses text boxes to accept data and the validation specifications for that data, write code that validates the user entries. 3. Use dialog boxes as needed within your applications.
  • 3. Murach’s C# 2010, C7 © 2010, Mike Murach & Associates, Inc.Slide 3 Objectives (continued) Knowledge 1. Describe the Exception hierarchy and name two of its subclasses. 2. Describe the use of try-catch statements to catch specific exceptions as well as all exceptions. 3. Describe the use of the properties and methods of an exception object. 4. Describe the use of throw statements. 5. Describe the three types of data validation that you’re most likely to perform on a user entry. 6. Describe two ways that you can use generic validation methods in a method that validates all of the user entries for a form.
  • 4. Murach’s C# 2010, C7 © 2010, Mike Murach & Associates, Inc.Slide 4 The dialog box for an unhandled exception
  • 5. Murach’s C# 2010, C7 © 2010, Mike Murach & Associates, Inc.Slide 5 The Exception hierarchy for five common exceptions System namespace Exception DivideByZeroExceptionOverflowException ArithmeticExceptionFormatException
  • 6. Murach’s C# 2010, C7 © 2010, Mike Murach & Associates, Inc.Slide 6 Methods that might throw exceptions Class Method Exception Convert ToDecimal(string) FormatException Convert ToInt32(string) FormatException Decimal Parse(string) FormatException DateTime Parse(string) FormatException
  • 7. Murach’s C# 2010, C7 © 2010, Mike Murach & Associates, Inc.Slide 7 The syntax to display a dialog box with an OK button MessageBox.Show(text[, caption]); A dialog box with an OK button The statement that displays this dialog box MessageBox.Show( "Please enter a valid number for the Subtotal field.", "Entry Error");
  • 8. Murach’s C# 2010, C7 © 2010, Mike Murach & Associates, Inc.Slide 8 The syntax for a simple try-catch statement try { statements } catch { statements } A try-catch statement try { decimal subtotal = Convert.ToDecimal(txtSubtotal.Text); decimal discountPercent = .2m; decimal discountAmount = subtotal * discountPercent; decimal invoiceTotal = subtotal - discountAmount; } catch { MessageBox.Show( "Please enter a valid number for the Subtotal " + "field.", "Entry Error"); }
  • 9. Murach’s C# 2010, C7 © 2010, Mike Murach & Associates, Inc.Slide 9 The dialog box that’s displayed if an exception occurs
  • 10. Murach’s C# 2010, C7 © 2010, Mike Murach & Associates, Inc.Slide 10 The syntax for a try-catch statement that accesses the exception try { statements } catch(ExceptionClass exceptionName) { statements } Two common properties for all exceptions Property Description Message Gets a message that briefly describes the current exception. StackTrace Gets a string that lists the methods that were called before the exception occurred. A common method for all exceptions Method Description GetType() Gets the type of the current exception.
  • 11. Murach’s C# 2010, C7 © 2010, Mike Murach & Associates, Inc.Slide 11 A try-catch statement that accesses the exception try { decimal subtotal = Convert.ToDecimal(txtSubtotal.Text); } catch(Exception ex) { MessageBox.Show( ex.Message + "nn" + ex.GetType().ToString() + "n" + ex.StackTrace, "Exception"); }
  • 12. Murach’s C# 2010, C7 © 2010, Mike Murach & Associates, Inc.Slide 12 The dialog box that’s displayed if an exception occurs
  • 13. Murach’s C# 2010, C7 © 2010, Mike Murach & Associates, Inc.Slide 13 The complete syntax for the try-catch statement try { statements } catch(MostSpecificException [exceptionName]) { statements }... [catch(NextMostSpecificException [exceptionName]) { statements }]... [catch([LeastSpecificException [exceptionName]]) { statements }] [finally { statements }]
  • 14. Murach’s C# 2010, C7 © 2010, Mike Murach & Associates, Inc.Slide 14 A try-catch statement that catches two specific exceptions try { decimal monthlyInvestment = Convert.ToDecimal(txtMonthlyInvestment.Text); decimal yearlyInterestRate = Convert.ToDecimal(txtInterestRate.Text); int years = Convert.ToInt32(txtYears.Text); } catch(FormatException) // a specific exception { MessageBox.Show( "A format exception has occurred. " + "Please check all entries.", "Entry Error"); }
  • 15. Murach’s C# 2010, C7 © 2010, Mike Murach & Associates, Inc.Slide 15 A try-catch statement that catches two specific exceptions (continued) catch(OverflowException) // another specific exception { MessageBox.Show( "An overflow exception has occurred. " + "Please enter smaller values.", "Entry Error"); } catch(Exception ex) // all other exceptions { MessageBox.Show(ex.Message, ex.GetType().ToString()); } finally // this code runs whether or not // an exception occurs { PerformCleanup(); }
  • 16. Murach’s C# 2010, C7 © 2010, Mike Murach & Associates, Inc.Slide 16 The syntax for throwing a new exception throw new ExceptionClass([message]); The syntax for throwing an existing exception throw exceptionName; When to throw an exception • When a method 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.
  • 17. Murach’s C# 2010, C7 © 2010, Mike Murach & Associates, Inc.Slide 17 A method that throws an exception when an exceptional condition occurs private decimal CalculateFutureValue( decimal monthlyInvestment, decimal interestRateMonthly, int months) { if (monthlyInvestment <= 0) throw new Exception("Monthly Investment must " + "be greater than 0."); if (interestRateMonthly <= 0) throw new Exception("Interest Rate must be " + "greater than 0."); . . }
  • 18. Murach’s C# 2010, C7 © 2010, Mike Murach & Associates, Inc.Slide 18 Code that throws an exception for testing purposes try { decimal subtotal = Convert.ToDecimal(txtSubtotal.Text); throw new Exception("An unknown exception " + "occurred."); } catch (Exception ex) { MessageBox.Show(ex.Message + "nn" + ex.GetType().ToString() + "n" + ex.StackTrace, "Exception"); }
  • 19. Murach’s C# 2010, C7 © 2010, Mike Murach & Associates, Inc.Slide 19 Code that rethrows an exception try { Convert.ToDecimal(txtSubtotal.Text); } catch (FormatException fe) { txtBox.Focus(); throw fe; }
  • 20. Murach’s C# 2010, C7 © 2010, Mike Murach & Associates, Inc.Slide 20 The code for the Future Value application with exception handling private void btnCalculate_Click(object sender, System.EventArgs e) { try { decimal monthlyInvestment = Convert.ToDecimal(txtMonthlyInvestment.Text); decimal yearlyInterestRate = Convert.ToDecimal(txtInterestRate.Text); int years = Convert.ToInt32(txtYears.Text); decimal monthlyInterestRate = yearlyInterestRate / 12 / 100; int months = years * 12; decimal futureValue = this.CalculateFutureValue( monthlyInvestment, monthlyInterestRate, months); txtFutureValue.Text = futureValue.ToString("c"); txtMonthlyInvestment.Focus(); }
  • 21. Murach’s C# 2010, C7 © 2010, Mike Murach & Associates, Inc.Slide 21 The code for the Future Value application with exception handling (continued) catch(FormatException) { MessageBox.Show( "Invalid numeric format. " + "Please check all entries.", "Entry Error"); } catch(OverflowException) { MessageBox.Show( "Overflow error. Please enter smaller values.", "Entry Error"); } catch(Exception ex) { MessageBox.Show( ex.Message, ex.GetType().ToString()); } }
  • 22. Murach’s C# 2010, C7 © 2010, Mike Murach & Associates, Inc.Slide 22 The code for the Future Value application with exception handling (continued) private decimal CalculateFutureValue( decimal monthlyInvestment, decimal monthlyInterestRate, int months) { decimal futureValue = 0m; for (int i = 0; i < months; i++) { futureValue = (futureValue + monthlyInvestment) * (1 + monthlyInterestRate); } return futureValue; }
  • 23. Murach’s C# 2010, C7 © 2010, Mike Murach & Associates, Inc.Slide 23 Code that checks that an entry has been made if (txtMonthlyInvestment.Text == "") { MessageBox.Show("Monthly Investment is a required " + "field.", Entry Error); txtMonthlyInvestment.Focus(); } Code that checks an entry for a valid decimal format try { Convert.ToDecimal(txtMonthlyInvestment.Text); } catch (FormatException) { MessageBox.Show( "Monthly Investment must be a numeric value.", "Entry Error"); txtMonthlyInvestment.Focus(); }
  • 24. Murach’s C# 2010, C7 © 2010, Mike Murach & Associates, Inc.Slide 24 Code that checks an entry for a valid range decimal monthlyInvestment = Convert.ToDecimal(txtMonthlyInvestment.Text); if (monthlyInvestment <= 0) { MessageBox.Show( "Monthly Investment must be greater than 0.", "Entry Error"); txtMonthlyInvestment.Focus(); } else if (monthlyInvestment >= 1000) { MessageBox.Show( "Monthly Investment must be less than 1,000.", "Entry Error"); txtMonthlyInvestment.Focus(); }
  • 25. Murach’s C# 2010, C7 © 2010, Mike Murach & Associates, Inc.Slide 25 A method that checks for a required field public bool IsPresent(TextBox textBox, string name) { if (textBox.Text == "") { MessageBox.Show(name + " is a required field.", "Entry Error"); textBox.Focus(); return false; } return true; }
  • 26. Murach’s C# 2010, C7 © 2010, Mike Murach & Associates, Inc.Slide 26 A method that checks for a valid numeric format public bool IsDecimal(TextBox textBox, string name) { try { Convert.ToDecimal(textBox.Text); return true; } catch(FormatException) { MessageBox.Show(name + " must be a decimal " + "value.", "Entry Error"); textBox.Focus(); return false; } }
  • 27. Murach’s C# 2010, C7 © 2010, Mike Murach & Associates, Inc.Slide 27 A method that checks for a valid numeric range public bool IsWithinRange(TextBox textBox, string name, decimal min, decimal max) { decimal number = Convert.ToDecimal(textBox.Text); if (number < min || number > max) { MessageBox.Show(name + " must be between " + min.ToString() + " and " + max.ToString() + ".", "Entry Error"); textBox.Focus(); return false; } return true; }
  • 28. Murach’s C# 2010, C7 © 2010, Mike Murach & Associates, Inc.Slide 28 Code that uses generic methods to check the validity of one entry if (IsPresent(txtMonthlyInvestment, "Monthly Investment") && IsDecimal(txtMonthlyInvestment, "Monthly Investment") && IsWithinRange(txtMonthlyInvestment, "Monthly Investment", 1, 1000)) { MessageBox.Show("Monthly Investment is valid.", "Test"); }
  • 29. Murach’s C# 2010, C7 © 2010, Mike Murach & Associates, Inc.Slide 29 Code that uses a series of simple if statements to validate multiple entries public bool IsValidData() { // Validate the Monthly Investment text box if (!IsPresent(txtMonthlyInvestment, "Monthly Investment")) return false; if (!IsDecimal(txtMonthlyInvestment, "Monthly Investment")) return false; if (!IsWithinRange(txtMonthlyInvestment, "Monthly Investment", 1, 1000)) return false; // Validate the Interest Rate text box if (!IsPresent(txtInterestRate, "Interest Rate")) return false; if (!IsDecimal(txtInterestRate, "Interest Rate")) return false; if (!IsWithinRange(txtInterestRate, "Interest Rate", 1, 20)) return false; return true; }
  • 30. Murach’s C# 2010, C7 © 2010, Mike Murach & Associates, Inc.Slide 30 Code that uses compound conditions in a single return statement to validate multiple entries public bool IsValidData() { return // Validate the Monthly Investment text box IsPresent(txtMonthlyInvestment, "Monthly Investment") && IsDecimal(txtMonthlyInvestment, "Monthly Investment") && IsWithinRange(txtMonthlyInvestment, "Monthly Investment", 1, 1000) && // Validate the Interest Rate text box IsPresent(txtInterestRate, "Yearly Interest Rate") && IsDecimal(txtInterestRate, "Yearly Interest Rate") && IsWithinRange(txtInterestRate, "Yearly Interest Rate", 1, 20); }
  • 31. Murach’s C# 2010, C7 © 2010, Mike Murach & Associates, Inc.Slide 31 The Future Value form with a dialog box for required fields
  • 32. Murach’s C# 2010, C7 © 2010, Mike Murach & Associates, Inc.Slide 32 The dialog box for invalid decimals The dialog box for invalid ranges
  • 33. Murach’s C# 2010, C7 © 2010, Mike Murach & Associates, Inc.Slide 33 The dialog box for an unanticipated exception
  • 34. Murach’s C# 2010, C7 © 2010, Mike Murach & Associates, Inc.Slide 34 The code for the Future Value application private void btnCalculate_Click(object sender, System.EventArgs e) { try { if (IsValidData()) { decimal monthlyInvestment = Convert.ToDecimal(txtMonthlyInvestment.Text); decimal yearlyInterestRate = Convert.ToDecimal(txtInterestRate.Text); int years = Convert.ToInt32(txtYears.Text); int months = years * 12; decimal monthlyInterestRate = yearlyInterestRate / 12 / 100; decimal futureValue = CalculateFutureValue( monthlyInvestment, monthlyInterestRate, months); txtFutureValue.Text = futureValue.ToString("c"); txtMonthlyInvestment.Focus(); } }
  • 35. Murach’s C# 2010, C7 © 2010, Mike Murach & Associates, Inc.Slide 35 The code for the Future Value application (cont.) catch(Exception ex) { MessageBox.Show(ex.Message + "nn" + ex.GetType().ToString() + "n" + ex.StackTrace, "Exception"); } } public bool IsValidData() { return IsPresent( txtMonthlyInvestment, "Monthly Investment") && IsDecimal( txtMonthlyInvestment, "Monthly Investment") && IsWithinRange(txtMonthlyInvestment, "Monthly Investment", 1, 1000) &&
  • 36. Murach’s C# 2010, C7 © 2010, Mike Murach & Associates, Inc.Slide 36 The code for the Future Value application (cont.) IsPresent(txtInterestRate, "Yearly Interest Rate") && IsDecimal(txtInterestRate, "Yearly Interest Rate") && IsWithinRange(txtInterestRate, "Yearly Interest Rate", 1, 20) && IsPresent(txtYears, "Number of Years") && IsInt32(txtYears, "Number of Years") && IsWithinRange(txtYears, "Number of Years", 1, 40); } public bool IsPresent(TextBox textBox, string name) { if (textBox.Text == "") { MessageBox.Show(name + " is a required field.", "Entry Error"); textBox.Focus(); return false; } return true; }
  • 37. Murach’s C# 2010, C7 © 2010, Mike Murach & Associates, Inc.Slide 37 The code for the Future Value application (cont.) public bool IsDecimal(TextBox textBox, string name) { try { Convert.ToDecimal(textBox.Text); return true; } catch(FormatException) { MessageBox.Show(name + " must be a decimal value.", "Entry Error"); textBox.Focus(); return false; } }
  • 38. Murach’s C# 2010, C7 © 2010, Mike Murach & Associates, Inc.Slide 38 The code for the Future Value application (cont.) public bool IsInt32(TextBox textBox, string name) { try { Convert.ToInt32(textBox.Text); return true; } catch(FormatException) { MessageBox.Show(name + " must be an integer.", "Entry Error"); textBox.Focus(); return false; } }
  • 39. Murach’s C# 2010, C7 © 2010, Mike Murach & Associates, Inc.Slide 39 The code for the Future Value application (cont.) public bool IsWithinRange(TextBox textBox, string name, decimal min, decimal max) { decimal number = Convert.ToDecimal(textBox.Text); if (number < min || number > max) { MessageBox.Show(name + " must be between " + min + " and " + max + ".", "Entry Error"); textBox.Focus(); return false; } return true; }
  • 40. Murach’s C# 2010, C7 © 2010, Mike Murach & Associates, Inc.Slide 40 The code for the Future Value application (cont.) private decimal CalculateFutureValue( decimal monthlyInvestment, decimal monthlyInterestRate, int months) { decimal futureValue = 0m; for (int i = 0; i < months; i++) { futureValue = (futureValue + monthlyInvestment) * (1 + monthlyInterestRate); } return futureValue; }