Chapter 3 Readings: 3.7 Simple Exception Handling
Fundamentals of Exception Handling in C
An exception is an unexpected error that occurs while a program is running. If an exception is not properly dealt with or handled by the program, the program will abruptly halt execution. Exceptions are usually caused by circumstances beyond the programmer's direct control, such as invalid user input.
Common Cause of Exceptions
A typical scenario leading to an exception involves user input in a user interface control:
A user enters a value into a
TextBoxcontrol, which is expected to represent a numeric value.The program invokes one of the numeric
Parsemethods (such asdouble.Parseorint.Parse) to convert the control'sTextproperty into a numeric data type.If the string contains invalid non-numeric characters (e.g., the string
wxyz), theParsemethod cannot perform the conversion.Because the
Parsemethod cannot continue operating, it throws an exception.
In standard programming terminology, a method is said to throw an exception when an unexpected error occurs and the method is incapable of continuing its normal operation.
Visual Studio Break Mode
When an application is executed inside Visual Studio (by clicking the Start Debugging button or pressing F5) and an unhandled exception occurs:
The application immediately stops running.
Visual Studio enters a special execution state called break mode.
An exception window appears displaying detailed error information. Below the window's title bar, a descriptive message explains the cause, such as:
Input string was not in a correct format.Visual Studio highlights the exact line of code that was executing when the exception was thrown.
To exit break mode and return Visual Studio to its normal editing mode, click the Stop Debugging button or press Shift + F5.
Structure and Execution of Try-Catch Statements
To prevent applications from crashing abruptly when errors occur, modern programming languages like C# utilize exception handlers. An exception handler is written using a try-catch statement.
General Syntax
The simplest variation of a try-catch statement follows this structure:
try
{
statement;
statement;
etc.
}
catch
{
statement;
statement;
etc.
}
Components and Execution Flow
tryblock: Begins with the keywordtryand contains one or more statements enclosed within braces{}. This block holds the code that could potentially throw an exception.catchclause and block: Follows immediately after thetryblock. It consists of the keywordcatchfollowed by one or more statements enclosed within braces{}.Execution Logic:
Statements inside the
tryblock execute sequentially in the order they are written.If all statements in the
tryblock execute successfully without throwing an exception, the entirecatchblock is completely skipped.If any statement inside the
tryblock throws an exception, normal execution halts immediately, and control jumps directly to thecatchclause, executing the statements inside thecatchblock.
Fuel Economy Application Example
Below is an implementation of a calculateButton_Click event handler utilizing a basic try-catch statement to catch parse errors when calculating miles per gallon (MPG):
private void calculateButton_Click(object sender, EventArgs e)
{
try
{
double miles; // To hold miles driven
double gallons; // To hold gallons used
double mpg; // To hold MPG
// Get the miles driven and assign it to the miles variable.
miles = double.Parse(milesTextBox.Text);
// Get the gallons used and assign it to the gallons variable.
gallons = double.Parse(gallonsTextBox.Text);
// Calculate MPG.
mpg = miles / gallons;
// Display the MPG in the mpgLabel control.
mpgLabel.Text = mpg.ToString();
}
catch
{
// Display an error message.
MessageBox.Show("Invalid data was entered.");
}
}
If the user enters non-numeric text into milesTextBox or gallonsTextBox, double.Parse throws an exception, causing execution to jump immediately to the catch block, which presents a dialog box with the message "Invalid data was entered.".
Accessing Exception Objects and Default Error Messages
When an exception is thrown, the system automatically instantiates an exception object in memory. This object encapsulates detailed data and properties regarding the specific error that occurred.
Assigning a Name to the Exception Object
To access the properties of the exception object inside a catch block, assign a variable name to the exception object within parentheses following the catch keyword:
catch (Exception ex)
Note: ex is a standard identifier variable name, but any valid C# variable identifier may be used.
The Message Property
The exception object contains a property named Message, which holds the system's default error message string describing the error.
Example Implementation
private void calculateButton_Click(object sender, EventArgs e)
{
try
{
double miles; // To hold miles driven
double gallons; // To hold gallons used
double mpg; // To hold MPG
// Get the miles driven and assign it to the miles variable.
miles = double.Parse(milesTextBox.Text);
// Get the gallons used and assign it to the gallons variable.
gallons = double.Parse(gallonsTextBox.Text);
// Calculate MPG.
mpg = miles / gallons;
// Display the MPG in the mpgLabel control.
mpgLabel.Text = mpg.ToString();
}
catch (Exception ex)
{
// Display the default error message.
MessageBox.Show(ex.Message);
}
}
Passing ex.Message to MessageBox.Show() displays system-generated messages such as Input string was not in a correct format. when conversion fails.
Tutorial 3-4: Test Average Application Implementation
Mathematical Calculation and Precedence Caution
Calculating an average requires summing all values and dividing by the total count of values.
Incorrect Expression: Error: Due to standard operator precedence, division takes place prior to addition. Value
cis divided by3.0, and the quotient is added toa + b.Correct Expression: Correction: Enclosing
a + b + cinside parentheses forces the addition operation to execute first before dividing by3.0.
User Interface Control Property Settings
Control Name | Control Type | Property Settings |
|---|---|---|
| Label |
|
| Label |
|
| Label |
|
| Label |
|
| TextBox | No properties changed |
| TextBox | No properties changed |
| TextBox | No properties changed |
| Label |
|
| Button |
|
| Button |
|
| Button |
|
| Form |
|
Complete Source Code (Program 3-4)
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 Test_Average
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void calculateButton_Click(object sender, EventArgs e)
{
try
{
double test1; // To hold test score #1
double test2; // To hold test score #2
double test3; // To hold test score #3
double average; // To hold the average test score
// Get the three test scores.
test1 = double.Parse(test1TextBox.Text);
test2 = double.Parse(test2TextBox.Text);
test3 = double.Parse(test3TextBox.Text);
// Calculate the average test score.
average = (test1 + test2 + test3) / 3.0;
// Display the average test score, with
// the output rounded to 1 decimal point.
averageLabel.Text = average.ToString("n1");
}
catch (Exception ex)
{
// Display the default error message.
MessageBox.Show(ex.Message);
}
}
private void clearButton_Click(object sender, EventArgs e)
{
// Clear the input and output controls.
test1TextBox.Text = "";
test2TextBox.Text = "";
test3TextBox.Text = "";
averageLabel.Text = "";
}
private void exitButton_Click(object sender, EventArgs e)
{
// Close the form.
this.Close();
}
}
}
Formatting Output
Passing the format string "n1" into the ToString() method (average.ToString("n1")) formats the resulting number into standard numeric format rounded to exactly one decimal place.
Checkpoint Questions and Review Answers
Checkpoint 3.36
Question: What can cause an application to throw an exception?
Answer: An application throws an exception when an unexpected error occurs at runtime that prevents a method from executing normally, such as when a user enters non-numeric text into a control that a Parse method attempts to convert into a numeric data type.
Checkpoint 3.37
Question: How do you get out of break mode when an exception is thrown?
Answer: You get out of break mode by clicking the Stop Debugging button on the toolbar or by pressing Shift + F5.
Checkpoint 3.38
Question: What kind of code does the try block of a try-catch statement contain?
Answer: The try block contains statements that could potentially throw an exception during execution.
Checkpoint 3.39
Question: What causes the program to jump to the catch clause and execute the catch block of a try-catch statement?
Answer: The program jumps to the catch clause when any statement inside the try block throws an exception.
Checkpoint 3.40
Question: How can you display the default error message when an exception is thrown?
Answer: You define an exception variable name in the catch clause, such as catch (Exception ex), and then access its Message property (e.g., MessageBox.Show(ex.Message);).
Checkpoint 3.41
Question: Write a try-catch statement for an application that calculates the sum of two whole numbers and displays the result. The application uses two TextBox controls named value1TextBox and value2TextBox to gather the input and a Label control named sumLabel to display the result.
Answer:
try
{
int value1;
int value2;
int sum;
value1 = int.Parse(value1TextBox.Text);
value2 = int.Parse(value2TextBox.Text);
sum = value1 + value2;
sumLabel.Text = sum.ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}