Question: Chapter 7-1 Lab Assignment: Add exception handling to the simple calculator. In this exercise, youll add exception handling to the Simple Calculator form of Chapter
Chapter 7-1 Lab Assignment: Add exception handling to the simple calculator.
In this exercise, youll add exception handling to the Simple Calculator form of Chapter 6-1 Lab Assignment.
1. If you have not already done so, create a Chapter 07 folder. Download the SimpleCalculator project With Exception Handling into the Chapter 07 folder and open the project in Visual Studio.
2. Add a try-catch statement in the btnCalculate_Click event handler that will catch any exceptions that occur when the statements in that event handler are executed. If an exception occurs, display a dialog box with the error message, the type of error, and a stack trace. Test the application by entering a nonnumeric value for one of the operands.
3. Add three additional catch blocks to the try-catch statement that will catch a FormatException, an OverflowException, and a DivideByZeroException. These catch blocks should display a dialog box with an appropriate error message.
4. Test the application again by entering a nonnumeric value for one of the operands. Then, enter 0 for the second operand as shown in the attached form to see what happens.
The code for 6-1 is noted below:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms;
namespace SimpleCalculator { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void btnCalculate_Click(object sender, System.EventArgs e) { decimal operand1 = Convert.ToDecimal(txtOperand1.Text); string operator1 = txtOperator.Text; decimal operand2 = Convert.ToDecimal(txtOperand2.Text); decimal result = Calculate(operand1, operator1, operand2);
result = Math.Round(result, 4); this.txtResult.Text = result.ToString(); txtOperand1.Focus(); }
private decimal Calculate(decimal operand1, string operator1, decimal operand2) { decimal result = 0; if (operator1 == "+") result = operand1 + operand2; else if (operator1 == "-") result = operand1 - operand2; else if (operator1 == "*") result = operand1 * operand2; else if (operator1 == "/") result = operand1 / operand2; return result; }
private void btnExit_Click(object sender, System.EventArgs e) { this.Close(); }
private void ClearResult(object sender, System.EventArgs e) { this.txtResult.Text = ""; } } }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
