How to handleHow to handle exceptions and validate dataenanawa/bcis222/slides/ch07slides.pdf · How...

36
Chapter 7 Chapter 7 How to handle How to handle exceptions and validate data Murach's C# 2012, C7 © 2013, Mike Murach & Associates, Inc. Slide 1

Transcript of How to handleHow to handle exceptions and validate dataenanawa/bcis222/slides/ch07slides.pdf · How...

Page 1: How to handleHow to handle exceptions and validate dataenanawa/bcis222/slides/ch07slides.pdf · How to handleHow to handle exceptions and validate data Murach's C# 2012, ... Murach's

Chapter 7Chapter 7

How to handleHow to handle exceptions and

validate data

Murach's C# 2012, C7 © 2013, Mike Murach & Associates, Inc. Slide 1

Page 2: How to handleHow to handle exceptions and validate dataenanawa/bcis222/slides/ch07slides.pdf · How to handleHow to handle exceptions and validate data Murach's C# 2012, ... Murach's

Objectives jApplied 1. Given a form that uses text boxes to accept data from the user, write

d h h i h i hcode 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.

Knowledge 1 Describe the Exception hierarchy and name two of its subclasses1. 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 D ib th f th ti d th d f ti3. Describe the use of the properties and methods of an exception

object.

Murach's C# 2012, C7 © 2013, Mike Murach & Associates, Inc. Slide 2

Page 3: How to handleHow to handle exceptions and validate dataenanawa/bcis222/slides/ch07slides.pdf · How to handleHow to handle exceptions and validate data Murach's C# 2012, ... Murach's

Objectives (cont.)j ( )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 entryperform 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# 2012, C7 © 2013, Mike Murach & Associates, Inc. Slide 3

Page 4: How to handleHow to handle exceptions and validate dataenanawa/bcis222/slides/ch07slides.pdf · How to handleHow to handle exceptions and validate data Murach's C# 2012, ... Murach's

The dialog box for an unhandled exceptiong p

Murach's C# 2012, C7 © 2013, Mike Murach & Associates, Inc. Slide 4

Page 5: How to handleHow to handle exceptions and validate dataenanawa/bcis222/slides/ch07slides.pdf · How to handleHow to handle exceptions and validate data Murach's C# 2012, ... Murach's

The Exception hierarchy p yfor five common exceptions

System namespaceExceptionException

ArithmeticExceptionFormatException

DivideByZeroExceptionOverflowException

Murach's C# 2012, C7 © 2013, Mike Murach & Associates, Inc. Slide 5

Page 6: How to handleHow to handle exceptions and validate dataenanawa/bcis222/slides/ch07slides.pdf · How to handleHow to handle exceptions and validate data Murach's C# 2012, ... Murach's

Methods that might throw exceptionsg pClass Method Exception Convert ToDecimal(string) FormatException OverflowException

Convert ToInt32(string) FormatException OverflowException

Decimal Parse(string) FormatException OverflowException

DateTime Parse(string) FormatException

Murach's C# 2012, C7 © 2013, Mike Murach & Associates, Inc. Slide 6

Page 7: How to handleHow to handle exceptions and validate dataenanawa/bcis222/slides/ch07slides.pdf · How to handleHow to handle exceptions and validate data Murach's C# 2012, ... Murach's

The syntax to display a dialog box y p y gwith an OK button

MessageBox.Show(text[, caption]);

A di l b ith OK b ttA dialog box with an OK button

The statement that displays this dialog box M B Sh (MessageBox.Show( "Please enter a valid number for the Subtotal field.", "Entry Error");

Murach's C# 2012, C7 © 2013, Mike Murach & Associates, Inc. Slide 7

Page 8: How to handleHow to handle exceptions and validate dataenanawa/bcis222/slides/ch07slides.pdf · How to handleHow to handle exceptions and validate data Murach's C# 2012, ... Murach's

The syntax for a simple try-catch statementy p ytry { statements } catch { statements }

A try-catch statementA try catch statementtry { 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# 2012, C7 © 2013, Mike Murach & Associates, Inc. Slide 8

Page 9: How to handleHow to handle exceptions and validate dataenanawa/bcis222/slides/ch07slides.pdf · How to handleHow to handle exceptions and validate data Murach's C# 2012, ... Murach's

The dialog box that’s displayed for an exceptiong p y p

Murach's C# 2012, C7 © 2013, Mike Murach & Associates, Inc. Slide 9

Page 10: How to handleHow to handle exceptions and validate dataenanawa/bcis222/slides/ch07slides.pdf · How to handleHow to handle exceptions and validate data Murach's C# 2012, ... Murach's

The syntax for a try-catch statement y ythat 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 M th d D i tiMethod DescriptionGetType() Gets the type of the current exception.

Murach's C# 2012, C7 © 2013, Mike Murach & Associates, Inc. Slide 10

Page 11: How to handleHow to handle exceptions and validate dataenanawa/bcis222/slides/ch07slides.pdf · How to handleHow to handle exceptions and validate data Murach's C# 2012, ... Murach's

A try-catch statement that accesses the exceptiony ptry { decimal subtotal =

Convert.ToDecimal(txtSubtotal.Text); Convert.ToDecimal(txtSubtotal.Text);} catch(Exception ex) { MessageBox.Show(ex.Message + "\n\n" + ex.GetType().ToString() + "\n" + ex.StackTrace, "Exception"); }

Murach's C# 2012, C7 © 2013, Mike Murach & Associates, Inc. Slide 11

Page 12: How to handleHow to handle exceptions and validate dataenanawa/bcis222/slides/ch07slides.pdf · How to handleHow to handle exceptions and validate data Murach's C# 2012, ... Murach's

The dialog box that’s displayed for an exceptiong p y p

Murach's C# 2012, C7 © 2013, Mike Murach & Associates, Inc. Slide 12

Page 13: How to handleHow to handle exceptions and validate dataenanawa/bcis222/slides/ch07slides.pdf · How to handleHow to handle exceptions and validate data Murach's C# 2012, ... Murach's

The complete syntax for the try-catch statementp y ytry { statements } catch(MostSpecificException [exceptionName]) { statements }... [catch(NextMostSpecificException [exceptionName]) { statements }]...[catch([LeastSpecificException [exceptionName]]) { statements }] [fi ll { t t t }][finally { statements }]

Murach's C# 2012, C7 © 2013, Mike Murach & Associates, Inc. Slide 13

Page 14: How to handleHow to handle exceptions and validate dataenanawa/bcis222/slides/ch07slides.pdf · How to handleHow to handle exceptions and validate data Murach's C# 2012, ... Murach's

A statement that catches two specific exceptionsp ptry { decimal monthlyInvestment = Convert.ToDecimal(txtMonthlyInvestment.Text); decimal yearlyInterestRate = y y Convert.ToDecimal(txtInterestRate.Text); int years = Convert.ToInt32(txtYears.Text); } catch(FormatException) // a specific exception {

MessageBox Show( MessageBox.Show( "A format exception has occurred. Please check all entries.", "Entry Error"); } catch(OverflowException) // another specific exception {

M B Sh ( 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# 2012, C7 © 2013, Mike Murach & Associates, Inc. Slide 14

}

Page 15: How to handleHow to handle exceptions and validate dataenanawa/bcis222/slides/ch07slides.pdf · How to handleHow to handle exceptions and validate data Murach's C# 2012, ... Murach's

The syntax for throwing a new exceptiony g pthrow new ExceptionClass([message]);

The syntax for throwing an existing exception throw exceptionName;

When to throw an exception Wh th d t it ti h it i ’t bl t• 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 handlerhandler.

• When you want to catch the exception, perform some processing, and then throw the exception again.

Murach's C# 2012, C7 © 2013, Mike Murach & Associates, Inc. Slide 15

Page 16: How to handleHow to handle exceptions and validate dataenanawa/bcis222/slides/ch07slides.pdf · How to handleHow to handle exceptions and validate data Murach's C# 2012, ... Murach's

A method that throws an exception pwhen an exceptional condition occurs

private decimal CalculateFutureValue( decimal monthlyInvestment,

decimal monthlyInterestRate int months) decimal monthlyInterestRate, int months){ if (monthlyInvestment <= 0) throw new Exception( "Monthly Investment must be greater than 0.");

if (monthl InterestRate < 0) if (monthlyInterestRate <= 0) throw new Exception( "Interest Rate must be greater than 0."); . . }}

Murach's C# 2012, C7 © 2013, Mike Murach & Associates, Inc. Slide 16

Page 17: How to handleHow to handle exceptions and validate dataenanawa/bcis222/slides/ch07slides.pdf · How to handleHow to handle exceptions and validate data Murach's C# 2012, ... Murach's

Code that throws an exception for testingp gtry { decimal subtotal = Convert.ToDecimal(txtSubtotal.Text);

throw new Exception("An unknown exception occurred."); throw new Exception( An unknown exception occurred. );} catch (Exception ex) { MessageBox.Show(ex.Message + "\n\n" + ex.GetType().ToString() + "\n" + ex.StackTrace, "Exception"); }

Murach's C# 2012, C7 © 2013, Mike Murach & Associates, Inc. Slide 17

Page 18: How to handleHow to handle exceptions and validate dataenanawa/bcis222/slides/ch07slides.pdf · How to handleHow to handle exceptions and validate data Murach's C# 2012, ... Murach's

Code that rethrows an exception ptry { Convert.ToDecimal(txtSubtotal.Text); }} catch (FormatException fe) { txtSubtotal.Focus(); throw fe;}

Murach's C# 2012, C7 © 2013, Mike Murach & Associates, Inc. Slide 18

Page 19: How to handleHow to handle exceptions and validate dataenanawa/bcis222/slides/ch07slides.pdf · How to handleHow to handle exceptions and validate data Murach's C# 2012, ... Murach's

The code for the Future Value application ppwith exception handling private void btnCalculate_Click(object sender, System.EventArgs e) {

try try { decimal monthlyInvestment = Convert.ToDecimal(txtMonthlyInvestment.Text); decimal yearlyInterestRate =

Con ert ToDecimal(t tInterestRate Te t) 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# 2012, C7 © 2013, Mike Murach & Associates, Inc. Slide 19

Page 20: How to handleHow to handle exceptions and validate dataenanawa/bcis222/slides/ch07slides.pdf · How to handleHow to handle exceptions and validate data Murach's C# 2012, ... Murach's

The code for the Future Value application ppwith exception handling (cont.) catch(FormatException) {

MessageBox Show( MessageBox.Show( "Invalid numeric format. Please check all entries.", "Entry Error"); } catch(OverflowException)

{ { MessageBox.Show( "Overflow error. Please enter smaller values.", "Entry Error"); }

h( i ) catch(Exception ex) { MessageBox.Show( ex.Message, ex.GetType().ToString()); } }

Murach's C# 2012, C7 © 2013, Mike Murach & Associates, Inc. Slide 20

Page 21: How to handleHow to handle exceptions and validate dataenanawa/bcis222/slides/ch07slides.pdf · How to handleHow to handle exceptions and validate data Murach's C# 2012, ... Murach's

The code for the Future Value application ppwith exception handling (cont.) private decimal CalculateFutureValue(decimal monthlyInvestment, decimal monthlyInterestRate, int months) {{ decimal futureValue = 0m; for (int i = 0; i < months; i++) { futureValue = (futureValue + monthlyInvestment)

* (1 + monthl InterestRate) * (1 + monthlyInterestRate); } return futureValue; }

Murach's C# 2012, C7 © 2013, Mike Murach & Associates, Inc. Slide 21

Page 22: How to handleHow to handle exceptions and validate dataenanawa/bcis222/slides/ch07slides.pdf · How to handleHow to handle exceptions and validate data Murach's C# 2012, ... Murach's

Code that checks that an entry has been madeyif (txtMonthlyInvestment.Text == "") { MessageBox.Show(

"Monthly Investment is a required field.", Monthly Investment is a required field. , "Entry Error"); txtMonthlyInvestment.Focus(); }

Code that checks an entry for a valid decimal value

decimal monthlyInvestment = 0m;if (!(Decimal.TryParse(txtMonthlyInvestment.Text, out monthlyInvestment))) { MessageBox.Show(

"M thl I t t t b i l " "Monthly Investment must be a numeric value.", "Entry Error"); txtMonthlyInvestment.Focus(); }

Murach's C# 2012, C7 © 2013, Mike Murach & Associates, Inc. Slide 22

Page 23: How to handleHow to handle exceptions and validate dataenanawa/bcis222/slides/ch07slides.pdf · How to handleHow to handle exceptions and validate data Murach's C# 2012, ... Murach's

Code that checks an entry for a valid rangey gdecimal 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(

hl b l h 1 000 "Monthly Investment must be less than 1,000.", "Entry Error"); txtMonthlyInvestment.Focus(); }

Murach's C# 2012, C7 © 2013, Mike Murach & Associates, Inc. Slide 23

Page 24: How to handleHow to handle exceptions and validate dataenanawa/bcis222/slides/ch07slides.pdf · How to handleHow to handle exceptions and validate data Murach's C# 2012, ... Murach's

A method that checks for a required fieldqpublic 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# 2012, C7 © 2013, Mike Murach & Associates, Inc. Slide 24

Page 25: How to handleHow to handle exceptions and validate dataenanawa/bcis222/slides/ch07slides.pdf · How to handleHow to handle exceptions and validate data Murach's C# 2012, ... Murach's

A method that checks for a valid numeric formatpublic bool IsDecimal(TextBox textBox, string name) { decimal number = 0m;

if (Decimal.TryParse(textBox.Text, out number)) if (Decimal.TryParse(textBox.Text, out number)) { return true; } else { MessageBox.Show( name + " must be a decimal value.", "Entry Error");

() textBox.Focus(); return false; } }

Murach's C# 2012, C7 © 2013, Mike Murach & Associates, Inc. Slide 25

Page 26: How to handleHow to handle exceptions and validate dataenanawa/bcis222/slides/ch07slides.pdf · How to handleHow to handle exceptions and validate data Murach's C# 2012, ... Murach's

A method that checks for a valid numeric rangegpublic bool IsWithinRange(TextBox textBox, string name, decimal min, decimal max) {

decimal number = Convert.ToDecimal(textBox.Text); 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; }

t t return true;}

Murach's C# 2012, C7 © 2013, Mike Murach & Associates, Inc. Slide 26

Page 27: How to handleHow to handle exceptions and validate dataenanawa/bcis222/slides/ch07slides.pdf · How to handleHow to handle exceptions and validate data Murach's C# 2012, ... Murach's

Code that checks the validity of one entryy yif (IsPresent(txtMonthlyInvestment, "Monthly Investment") && IsDecimal(txtMonthlyInvestment,

"Monthly Investment") && Monthly Investment ) && IsWithinRange(txtMonthlyInvestment, "Monthly Investment", 1, 1000)) { MessageBox.Show( "Monthly Investment is valid.", "Test"); }

Murach's C# 2012, C7 © 2013, Mike Murach & Associates, Inc. Slide 27

Page 28: How to handleHow to handle exceptions and validate dataenanawa/bcis222/slides/ch07slides.pdf · How to handleHow to handle exceptions and validate data Murach's C# 2012, ... Murach's

Code that uses a series of simple if statementsppublic bool IsValidData() { // Validate the Monthly Investment text box if (!IsPresent(txtMonthlyInvestment, "Monthly Investment"))

t f l 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# 2012, C7 © 2013, Mike Murach & Associates, Inc. Slide 28

Page 29: How to handleHow to handle exceptions and validate dataenanawa/bcis222/slides/ch07slides.pdf · How to handleHow to handle exceptions and validate data Murach's C# 2012, ... Murach's

Compound conditions in a single return statementp gpublic bool IsValidData() { return

// lid h hl b // 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# 2012, C7 © 2013, Mike Murach & Associates, Inc. Slide 29

Page 30: How to handleHow to handle exceptions and validate dataenanawa/bcis222/slides/ch07slides.pdf · How to handleHow to handle exceptions and validate data Murach's C# 2012, ... Murach's

The Future Value form with a dialog box gfor required fields

Murach's C# 2012, C7 © 2013, Mike Murach & Associates, Inc. Slide 30

Page 31: How to handleHow to handle exceptions and validate dataenanawa/bcis222/slides/ch07slides.pdf · How to handleHow to handle exceptions and validate data Murach's C# 2012, ... Murach's

The dialog box for invalid decimalsg

The dialog box for invalid ranges

Murach's C# 2012, C7 © 2013, Mike Murach & Associates, Inc. Slide 31

Page 32: How to handleHow to handle exceptions and validate dataenanawa/bcis222/slides/ch07slides.pdf · How to handleHow to handle exceptions and validate data Murach's C# 2012, ... Murach's

The dialog box for an unanticipated exceptiong p p

Murach's C# 2012, C7 © 2013, Mike Murach & Associates, Inc. Slide 32

Page 33: How to handleHow to handle exceptions and validate dataenanawa/bcis222/slides/ch07slides.pdf · How to handleHow to handle exceptions and validate data Murach's C# 2012, ... Murach's

The code for the Future Value applicationppprivate 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 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(); } } catch(Exception ex) { MessageBox.Show(ex.Message + "\n\n" + ex.GetType().ToString() + "\n" + ex.StackTrace, "Exception"); } }

Murach's C# 2012, C7 © 2013, Mike Murach & Associates, Inc. Slide 33

}

Page 34: How to handleHow to handle exceptions and validate dataenanawa/bcis222/slides/ch07slides.pdf · How to handleHow to handle exceptions and validate data Murach's C# 2012, ... Murach's

The code for the Future Value application (cont.)pp ( )public bool IsValidData() { return IsPresent(txtMonthlyInvestment, "Monthly Investment") && IsDecimal(txtMonthlyInvestment, "Monthly Investment") &&y y IsWithinRange(txtMonthlyInvestment, "Monthly Investment", 1, 1000) && 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); }

bli b l I P t(T tB t tB t i )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# 2012, C7 © 2013, Mike Murach & Associates, Inc. Slide 34

Page 35: How to handleHow to handle exceptions and validate dataenanawa/bcis222/slides/ch07slides.pdf · How to handleHow to handle exceptions and validate data Murach's C# 2012, ... Murach's

The code for the Future Value application (cont.)pp ( )public bool IsDecimal(TextBox textBox, string name) { decimal number = 0m; if (Decimal.TryParse(textBox.Text, out number)) { return true; } else { MessageBox.Show(name + " must be a decimal value.", "Entry Error");

textBox Focus(); textBox.Focus(); return false; } } public bool IsInt32(TextBox textBox, string name) {

i t b 0 int number = 0; if (Int32.TryParse(textBox.Text, out number)) { return true; } else { MessageBox.Show(name + " must be an integer.", "Entry Error"); textBox.Focus(); return false; } }

Murach's C# 2012, C7 © 2013, Mike Murach & Associates, Inc. Slide 35

}

Page 36: How to handleHow to handle exceptions and validate dataenanawa/bcis222/slides/ch07slides.pdf · How to handleHow to handle exceptions and validate data Murach's C# 2012, ... Murach's

The code for the Future Value application (cont.)pp ( )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; } 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# 2012, C7 © 2013, Mike Murach & Associates, Inc. Slide 36