Visual C#

.NET Framework Support for Exception Handling

The .NET Framework provides various classes to handle almost any type of exception you can think of. There are so many of these classes that we can only…

17 min read3,646 words12 code samples

A Review of .NET Exception Classes#

Introduction#

The .NET Framework includes an extensive set of classes designed to manage virtually any exception. Since there are so many, we will focus on the ones most relevant to our applications. You can handle exceptions in two primary ways: if a specific error is expected, you can catch it using a catch() block—optionally without naming the argument—and then provide a tailored message. Alternatively, you can use the throw keyword to manually raise an exception, which we will explore later. Moving forward, we will highlight the specific exceptions that might occur in our code.

The Format Exception#

Everything the user types into an application using the keyboard is primarily a string and you must convert it to the appropriate type before using it. When you request a specific type of value from the user, after the user has typed it and you decide to convert it to the appropriate type, if your conversion fails, the program produces (we will use he word "throw") an error. The error is of from the FormatException class. Here is a program that deals with a FormatException exception:

C#
private void button1_Click(object sender, System.EventArgs e)
{
	double Number;

	try 
	{
		Number = double.Parse(textBox1.Text);

		textBox2.Text = (Number * 2).ToString();
	}
	catch(FormatException)
	{
		MessageBox.Show("You typed an invalid number");
	}
}

Practical Learning: Using the FormatException Class

  1. Open the GeorgetownCleaningServices1 application from the previous lesson
  2. Change the form's file as follows: private void btnProcess_Click(object sender, EventArgs e) { if (this.btnProcess.Text == "Process") { this.Height = 408; this.btnProcess.Text = "Reset"; } else { this.Height = 232; this.txtCustomerName1.Text = ""; this.txtMM.Text = "1"; this.txtDD.Text = "1"; this.txtYYYY.Text = "2000"; this.txtQtyShirts.Text = "0"; this.txtQtyPants.Text = "0"; this.txtQtyOther.Text = "0"; this.txtSubTotalShirts.Text = "0.00"; this.txtSubTotalPants.Text = "0.00"; this.txtSubTotalOther.Text = "0.00"; this.btnProcess.Text = "Process"; } // Request order information from the user CustomerName = this.txtCustomerName1.Text; mm = this.txtMM.Text; dd = this.txtDD.Text; yyyy = this.txtYYYY.Text; // Request the quantity of each category of items // Number of Shirts try { NumberOfShirts = uint.Parse(this.txtQtyShirts.Text); } catch (FormatException) { MessageBox.Show("The value you typed for the number of " + "shirts is not a valid number." + "\nPlease enter a natural number such " + "as 2 or 24 or even 248"); } // Number of Pants try { NumberOfPants = uint.Parse(this.txtQtyPants.Text); } catch (FormatException) { MessageBox.Show("The value you typed for the number of " + "pair or pants is not a valid number." + "\nPlease enter a natural number such " + "as 2 or 24 or even 248"); } // Number of Dresses try { NumberOfOther = uint.Parse(this.txtQtyOther.Text); } catch (FormatException) { MessageBox.Show("The value you typed for the number of " + "other items is not a valid number." + "\nPlease enter a natural number such " + "as 2 or 24 or even 248"); } // Unit Prices of items try { PriceOneShirt = decimal.Parse(this.txtUnitPriceShirts.Text); } catch (FormatException) { MessageBox.Show("The value you entered for the unit price " + "of a shirt is not a recognizable currency " + "amount.\nOnly natural or decimal numbers " + "are allowed. Please consult the management " + "to know the valid prices."); } try { PriceAPairOfPants = decimal.Parse(this.txtUnitPricePants.Text); } catch (FormatException) { MessageBox.Show("The value you entered for the unit price of " + "a pair of pants is not a recognizable " + "currency amount.\nOnly natural or decimal " + "numbers are allowed. You can consult the " + "management to find out about " + "the allowable prices."); } try { PriceOther = decimal.Parse(this.txtUnitPriceOther.Text); } catch (FormatException) { MessageBox.Show("The value you entered for the unit " + "price of other items is not a valid amount." + "\nYou must enter only a natural or a " + "decimal number. For more information, " + "please consult the management to get " + "the right prices."); } // Perform the necessary calculations SubTotalShirts = NumberOfShirts * PriceOneShirt; SubTotalPants = NumberOfPants * PriceAPairOfPants; SubTotalOther = NumberOfOther * PriceOther; this.txtSubTotalShirts.Text = SubTotalShirts.ToString(); this.txtSubTotalPants.Text = SubTotalPants.ToString(); this.txtSubTotalOther.Text = SubTotalOther.ToString(); // Calculate the "temporary" total of the order TotalOrder = SubTotalShirts + SubTotalPants + SubTotalOther; // Display the receipt this.txtCustomerName2.Text = CustomerName; this.txtOrderDate.Text = mm + "/" + dd + "/" + yyyy; this.txtTotalOrder.Text = TotalOrder.ToString(); } private void btnTax_Click(object sender, EventArgs e) { // Get the tax rate try { TaxRate = decimal.Parse(this.txtTaxRate.Text) / 100; } catch (FormatException) { MessageBox.Show("The value you entered is not " + "recognized as a valid tax rate." + "\nA valid tax rate is a value " + "between 0 and 100.00" + "\nPlease try again."); } // Calculate the tax amount using a constant rate TaxAmount = TotalOrder * TaxRate; // Add the tax amount to the total order SalesTotal = TotalOrder + TaxAmount; this.txtTaxAmount.Text = TaxAmount.ToString("F"); this.txtNetPrice.Text = SalesTotal.ToString("F"); } private void btnDifference_Click(object sender, EventArgs e) { decimal AmountTended = 0.00M, Difference = 0.00M; // Request money for the order try { AmountTended = decimal.Parse(this.txtAmountTended.Text); } catch (FormatException) { MessageBox.Show("The value you entered for the amount " + "tended is not valid. Only natural or " + "decimal numbers are allowed." + "Please try again."); } // Calculate the difference owed to the customer // or that the customer still owes to the store Difference = AmountTended - SalesTotal; this.txtDifference.Text = Difference.ToString("F"); }
  3. Execute the application and return to your programming environment

The Overflow Exception#

A computer application receives, processes, and produces values on a regular basis as the program is running. To better manage these values, as we saw when studying variables and data types in Lesson 2, the compiler uses appropriate amounts of space to store its values. It is not unusual that either you the programmer or a user of your application provides an value that is beyond the allowed range based on the data type. For example, we saw that a byte uses 8 bits to store a value and a combination of 8 bits can store a number no more than 255. If you provide a value higher than 255 to be stored in a byte, you get an error. Consider the following program:

C#
private void button1_Click(object sender, System.EventArgs e)
{
	byte NumberOfPages;

	NumberOfPages = byte.Parse(this.textBox1.Text);

	this.textBox2.Text = NumberOfPages.ToString();
}

When a value beyond the allowable range is asked to be stored in memory, the compiler produces (the verb is "throws" as we will learn soon) an error of the OverflowException class. Here is an example of running the program with a bad number:

As with the other errors, when this exception is thrown, you should take appropriate action.

The Argument Out of Range Exception#

Once again, we know that a value is passed to the Parse() method of its data type for analysis. For a primitive data type, the Parse() method scans the string and if the string cannot be converted into a valid character or number, the compiler usually throws a FormatException exception as we saw above. Other classes such as DateTime also use a Parse() method to scan the value submitted to it. For example, if you request a date value from the user, the DateTime.Parse() method scans the string to validate it. In US English, Parse() expects the user to type a string in the form m/d/yy or mm/dd/yy or mm/dd/yyyy. Consider the following program:

C#
private void button1_Click(object sender, System.EventArgs e)
{
	DateTime DateHired;

	DateHired = DateTime.Parse(this.textBox1.Text);

	this.textBox2.Text = DateHired.ToString();
}

If the user types a value that cannot be converted into a valid date, the compiler throws an ArgumentOutOfRangeException exception. Here is an example of running the above program with an invalid date:

One way you can avoid this is to guide the user but still take appropriate actions, just in case this error is thrown. Practical Learning: Using an ArgumentOutOfRangeException

  1. Right-click the form and click View Code
  2. Under the CustomerName variable, declare a variable named OrderTime of type DateTime namespace GeorgetownCleaningServices1 { public partial class Form1 : Form { // Order Information string CustomerName; DateTime OrderDate; // Quantities of items uint NumberOfShirts; uint NumberOfPants; uint NumberOfOther;
  3. Change the Click event of the Process button as follows: private void btnProcess_Click(object sender, EventArgs e) { if (this.btnProcess.Text == "Process") { this.Height = 408; this.btnProcess.Text = "Reset"; } else { this.Height = 232; this.txtCustomerName1.Text = ""; this.txtMM.Text = "1"; this.txtDD.Text = "1"; this.txtYYYY.Text = "2000"; this.txtQtyShirts.Text = "0"; this.txtQtyPants.Text = "0"; this.txtQtyOther.Text = "0"; this.txtSubTotalShirts.Text = "0.00"; this.txtSubTotalPants.Text = "0.00"; this.txtSubTotalOther.Text = "0.00"; this.btnProcess.Text = "Process"; } // Request order information from the user CustomerName = this.txtCustomerName1.Text; try { int mm, dd, yyyy; mm = int.Parse(this.txtMM.Text); dd = int.Parse(this.txtDD.Text); yyyy = int.Parse(this.txtYYYY.Text); OrderDate = new DateTime(yyyy, mm, dd); } catch (ArgumentOutOfRangeException) { MessageBox.Show("The date you entered is not valid" + "- Please try again!"); } . . . No Change // Display the receipt this.txtCustomerName2.Text = CustomerName; this.txtOrderDate.Text = OrderDate.ToString("D") ; this.txtTotalOrder.Text = TotalOrder.ToString(); }
  4. Execute the application.
  5. To test it enter valid and invalid values for the controls. Here is an example:
  6. Close the form and return to your programming environment

The Divide by Zero Exception#

Division by zero is an operation to always avoid. It is so important that it is one of the most fundamental exceptions of the computer. It is addressed at the core level even by the Intel and AMD processors. It is also addressed by the operating systems at their level. It is also addressed by most, if not all, compilers. It is also addressed by most, if not, all libraries. This means that this exception is never welcomed anywhere. The .NET Framework also provides it own class to face this operation. If an attempt to divide a value by 0, the compiler throws a DivideByZeroException exception. We will see an example later.

Techniques of Using Exceptions#

Throwing an Exception#

As mentioned above, the Exception class is equipped with a Message property that carried a message for the error that occurred. We also mentioned that the message of this property may not be particularly useful to a user. Fortunately, you can create your own message and pass it to the Exception. To be able to receive custom messages, the Exception class provides the following constructor:

C#
public Exception(string message);

To use it, in the section that you are anticipating the error, type the throw keyword followed by a new instance of the Exception class using the constructor that takes a string. Here is an example:

C#
private void button1_Click(object sender, System.EventArgs e)
{
        double Operand1, Operand2;
        double Result = 0.00;
        string Operator;
    
        try 
        {
	Operand1 = double.Parse(this.txtNumber1.Text);
	Operator = this.txtOperator.Text;
	Operand2 = double.Parse(this.txtNumber2.Text);

	if( Operator != "+" && Operator != "-" && Operator != "*" && Operator != "/" )
		throw new Exception(Operator);

	switch(Operator)
	{
	case "+":
		Result = Operand1 + Operand2;
		break;
	case "-":
		Result = Operand1 - Operand2;
		break;
	case "*":
		Result = Operand1 * Operand2;
		break;
	case "/":
		Result = Operand1 / Operand2;
		break;
	default:
		MessageBox.Show("Bad Operation");
		break;
	}

	this.txtResult.Text = Result.ToString();
        }
        catch(Exception ex)
        {
	MessageBox.Show("Operation Error: " + ex.Message + " is not a valid operator");
        }
}

Catching Various Exceptions#

In the previous examples, we used a single catch block to let the compiler handle errors as they occurred. However, a method with complex operations might produce several different types of errors. To address this, you can define multiple catch sections, each tailored to a specific exception type. The basic formula is:

C#
try {
	// Code to Try
}
catch(Arg1)
{
	// One Exception
}
catch(Arg2)
{
	// Another Exception
}

The compiler would proceed in a top-down:

  1. Following the normal flow of the program, the compiler enters the try block
  2. If no exception occurs in the try block, the rest of the try block is executed If an exception occurs in the try block, the compiler registers the type of error that occurred. If there is a throw line, the compiler registers it also: The compiler gets out of the try section The compiler examines the first catch . If the first catch matches the thrown error, that catch executes and the exception handling routine may seize. If the first catch doesn’t match the thrown error, the compiler proceeds with the next catch The compiler checks the next match, if any and proceeds as in the first match. This continues until the compiler finds a catch that matches the thrown error If one of the catches matches the thrown error, its body executes. If no catch matches the thrown error, the compiler calls the Exception class and uses the default message

Multiple catches are written if or when a try block is expected to throw different types of errors. For example, in our calculator, we want to consider only the addition, the subtraction, the multiplication, and the division. It is also likely that the user may type one or two invalid numbers. This leads us to know that our program can produce at least two types of errors at this time. Based on this, we can address them using two catch clauses as follows:

C#
private void button1_Click(object sender, System.EventArgs e)
{
        double Operand1, Operand2;
        double Result = 0.00;
        string Operator;

        try 
        {
	Operand1 = double.Parse(this.txtNumber1.Text);
	Operator = this.txtOperator.Text;
	Operand2 = double.Parse(this.txtNumber2.Text);

	if( Operator != "+" && Operator != "-" && Operator != "*" && Operator != "/" )
		throw new Exception(Operator);

	switch(Operator)
	{
	case "+":
		Result = Operand1 + Operand2;
		break;
	case "-":
		Result = Operand1 - Operand2;
		break;
	case "*":
		Result = Operand1 * Operand2;
		break;
	case "/":
		Result = Operand1 / Operand2;
		break;
	default:
		MessageBox.Show("Bad Operation");
		break;
	}

	this.txtResult.Text = Result.ToString();
        }
        catch(FormatException)
        {
	MessageBox.Show("You type an invalid number. Please correct it");
        }
        catch(Exception ex)
        {
	MessageBox.Show("Operation Error: " + ex.Message + " is not a valid operator");
        }
}

This program works fine as long as the user types two valid numbers and a valid arithmetic operator. Anything else, such an invalid number or an unexpected operator would cause an error to be thrown:

Obviously various bad things could happen when this program is running. Imagine that the user wants to perform a division. You need to tell the compiler what to do if the user enters the denominator as 0 (or 0.00). If this happens, one of the options you should consider is to display a message and get out. Fortunately, the .NET Framework provides the DivideByZeroException class to deal with an exception caused by division by zero. As done with the message passed to the Exception class, you can compose your own message and pass it to the DivideByZeroException(string message) constructor. Exception is the parent of all exception classes. This corresponds to the three periods of a C++' catch(...) block. Therefore, if you write various catch blocks, the one that takes the Exception as argument should be the last. Here is an example that catches two types of exceptions:

C#
private void button1_Click(object sender, System.EventArgs e)
{
        double Operand1, Operand2;
        double Result = 0.00;
        string Operator;

        try 
       {
	Operand1 = double.Parse(this.txtNumber1.Text);
	Operator = this.txtOperator.Text;
	Operand2 = double.Parse(this.txtNumber2.Text);

	if( Operator != "+" && Operator != "-" && Operator != "*" && Operator != "/" )
		throw new Exception(Operator);

	switch(Operator)
	{
	case "+":
	        Result = Operand1 + Operand2;
	        break;
	case "-":
	        Result = Operand1 - Operand2;
	        break;
	case "*":
	        Result = Operand1 * Operand2;
	        break;
	case "/":
	        if( Operand2 == 0 )
		throw new DivideByZeroException("Division by zero is not allowed");
	        Result = Operand1 / Operand2;
	        break;
	default:
	        MessageBox.Show("Bad Operation");
	        break;
	}

	this.txtResult.Text = Result.ToString();
        }
        catch(FormatException)
        {
	MessageBox.Show("You type an invalid number. Please correct it");
        }
        catch(DivideByZeroException ex)
        {
	MessageBox.Show(ex.Message);
        }
        catch(Exception ex)
        {
	MessageBox.Show("Operation Error: " + ex.Message + " is not a valid operator");
        }
}

Practical Learning: Identifying the Thrown Exception

  1. To catch various exceptions, change the form's file as follows: private void btnProcess_Click(object sender, EventArgs e) { if (this.btnProcess.Text == "Process") { this.Height = 408; this.btnProcess.Text = "Reset"; } else { this.Height = 232; this.txtCustomerName1.Text = ""; this.txtMM.Text = "1"; this.txtDD.Text = "1"; this.txtYYYY.Text = "2000"; this.txtQtyShirts.Text = "0"; this.txtQtyPants.Text = "0"; this.txtQtyOther.Text = "0"; this.txtSubTotalShirts.Text = "0.00"; this.txtSubTotalPants.Text = "0.00"; this.txtSubTotalOther.Text = "0.00"; this.btnProcess.Text = "Process"; } // Request order information from the user CustomerName = this.txtCustomerName1.Text; try { int mm, dd, yyyy; mm = int.Parse(this.txtMM.Text); dd = int.Parse(this.txtDD.Text); yyyy = int.Parse(this.txtYYYY.Text); OrderDate = new DateTime(yyyy, mm, dd); } // This exception is thrown if the user types a value that cannot // be converted into a valid number catch (FormatException ex) { MessageBox.Show("Error: " + ex.Message + "\nThe value you entered " + "is not a valid number"); } // This exception is thrown if the values that user had typed cannot // produce a valid date value catch (ArgumentOutOfRangeException) { MessageBox.Show("The date you entered is not " + "valid - Please try again!"); } // Request the quantity of each category of items // Number of Shirts try { NumberOfShirts = uint.Parse(this.txtQtyShirts.Text); } // This exception is thrown if the user typed a value that cannot // be recognized as a valid number catch (FormatException) { MessageBox.Show("The value you typed for the number of " + "shirts is not a valid number." + "\nPlease enter a natural number " + "such as 2 or 24 or even 248"); } // This exception is thrown if the user types a negative value catch (OverflowException) { MessageBox.Show("The number you typed is negative but " + "we cannot accept a negative number of shirts"); } // Number of Pants try { NumberOfPants = uint.Parse(this.txtQtyPants.Text); } catch (FormatException) { MessageBox.Show("The value you typed for the number of " + "pair or pants is not a valid number." + "\nPlease enter a natural number such " + "as 2 or 24 or even 248"); } catch (OverflowException) { MessageBox.Show("The number you typed is negative but " + "we cannot accept a negative number of shirts"); } // Number of Dresses try { NumberOfOther = uint.Parse(this.txtQtyOther.Text); } catch (FormatException) { MessageBox.Show("The value you typed for the number of " + "other items is not a valid number." + "\nPlease enter a natural number such " + "as 2 or 24 or even 248"); } catch (OverflowException) { MessageBox.Show("The number you typed is negative but " + "we cannot accept a negative number of shirts"); } // Unit Prices of items try { PriceOneShirt = decimal.Parse(this.txtUnitPriceShirts.Text); if (PriceOneShirt < 0) throw new Exception("Negative numbers are not allowed " + "for the price of a shirt"); } catch (FormatException) { MessageBox.Show("The value you entered for the unit price " + "of a shirt is not a recognizable currency " + "amount.\nOnly natural or decimal numbers " + "are allowed. Please consult the management " + "to know the valid prices."); } catch (Exception ex) { MessageBox.Show(ex.Message); } try { PriceAPairOfPants = decimal.Parse(this.txtUnitPricePants.Text); if (PriceAPairOfPants < 0) throw new Exception("Negative numbers are not allowed " + "for the price of a pair of pants"); } catch (FormatException) { MessageBox.Show("The value you entered for the unit price of " + "a pair of pants is not a recognizable " + "currency amount.\nOnly natural or decimal " + "numbers are allowed. You can consult the " + "management to find out about " + "the allowable prices."); } catch (Exception ex) { MessageBox.Show(ex.Message); } try { PriceOther = decimal.Parse(this.txtUnitPriceOther.Text); if (PriceOther < 0) throw new Exception("Negative numbers are " + "not allowed for the price"); } catch (FormatException) { MessageBox.Show("The value you entered for the unit " + "price of other items is not a valid amount." + "\nYou must enter only a natural or a " + "decimal number. For more information, " + "please consult the management to get " + "the right prices."); } catch (Exception ex) { MessageBox.Show(ex.Message); } // Perform the necessary calculations SubTotalShirts = NumberOfShirts * PriceOneShirt; SubTotalPants = NumberOfPants * PriceAPairOfPants; SubTotalOther = NumberOfOther * PriceOther; this.txtSubTotalShirts.Text = SubTotalShirts.ToString(); this.txtSubTotalPants.Text = SubTotalPants.ToString(); this.txtSubTotalOther.Text = SubTotalOther.ToString(); // Calculate the "temporary" total of the order TotalOrder = SubTotalShirts + SubTotalPants + SubTotalOther; // Display the receipt this.txtCustomerName2.Text = CustomerName; this.txtOrderDate.Text = OrderDate.ToString("D"); this.txtTotalOrder.Text = TotalOrder.ToString(); } private void btnTax_Click(object sender, EventArgs e) { // Get the tax rate try { TaxRate = decimal.Parse(this.txtTaxRate.Text) / 100; if (TaxRate < 0) throw new Exception("Negative numbers are not " + "allowed for a tax rate"); } catch (FormatException) { MessageBox.Show("The value you entered is not " + "recognized as a valid tax rate." + "\nA valid tax rate is a value " + "between 0 and 100.00" + "\nPlease try again."); } catch (Exception ex) { MessageBox.Show(ex.Message); } // Calculate the tax amount using a constant rate TaxAmount = TotalOrder * TaxRate; // Add the tax amount to the total order SalesTotal = TotalOrder + TaxAmount; this.txtTaxAmount.Text = TaxAmount.ToString("F"); this.txtNetPrice.Text = SalesTotal.ToString("F"); } private void btnDifference_Click(object sender, EventArgs e) { decimal AmountTended = 0.00M, Difference = 0.00M; // Request money for the order try { AmountTended = decimal.Parse(this.txtAmountTended.Text); if (AmountTended < 0) throw new Exception("Negative numbers are not " + "allowed forthe amount tended"); } catch (FormatException) { MessageBox.Show("The value you entered for the amount " + "tended is not valid. Only natural or " + "decimal numbers are allowed." + "Please try again."); } catch (Exception ex) { MessageBox.Show(ex.Message); } // Calculate the difference owed to the customer // or that the customer still owes to the store Difference = AmountTended - SalesTotal; this.txtDifference.Text = Difference.ToString("F"); } } }
  2. Test the application and return to your programming environment

Exceptions Nesting#

The calculator simulator we have studied so far performs a division as one of its assignments. We learned that, in order to perform any operation, the compiler must first make sure that the user has entered a valid operator. Provided the operator is one of those we are expecting, we also must make sure that the user typed valid numbers. Even if these two criteria are met, it was possible that the user enter 0 for the denominator. The block that is used to check for a non-zero denominator depends on the exception that validates the operators. The exception that could result from a zero denominator depends on the user first entering a valid number for the denominator. You can create an exception inside of another. This is referred to as nesting an exception. This is done by applying the same techniques we used to nest conditional statements. This means that you can write an exception that depends on, and is subject to, another exception. To nest an exception, write a try block in the body of the parent exception. The nested try block must be followed by its own catch(es) clause. To effectively handle the exception, make sure you include an appropriate throw in the try block. Here is an example:

C#
private void button1_Click(object sender, System.EventArgs e)
{
        double Operand1, Operand2;
        double Result = 0.00;
        string Operator;

        try 
        {
	Operand1 = double.Parse(this.txtNumber1.Text);
	Operator = this.txtOperator.Text;
	Operand2 = double.Parse(this.txtNumber2.Text);

	if( Operator != "+" && Operator != "-" && Operator != "*" && Operator != "/" )
		throw new Exception(Operator);

	switch(Operator)
	{
	case "+":
		Result = Operand1 + Operand2;
		this.txtResult.Text = Result.ToString();
		break;
	case "-":
		Result = Operand1 - Operand2;
		this.txtResult.Text = Result.ToString();
		break;
	case "*":
		Result = Operand1 * Operand2;
		this.txtResult.Text = Result.ToString();
		break;
	case "/":
	        try 
	       {
		if( Operand2 == 0 )
		    throw new DivideByZeroException("Division by zero is not allowed");
		Result = Operand1 / Operand2;
		this.txtResult.Text = Result.ToString();
	        }
	        catch(DivideByZeroException ex)
	        {
		MessageBox.Show(ex.Message);
	        }
	        break;
	default:
	        MessageBox.Show("Bad Operation");
	        break;
               }
        }
        catch(FormatException)
        {
	MessageBox.Show("You type an invalid number. Please correct it");
        }
        catch(Exception ex)
        {
	MessageBox.Show("Operation Error: " + ex.Message + " is not a valid operator");
        }
}

Exceptions and Methods#

One of the most effective techniques used to deal with code is to isolate assignments. We have learned this when studying methods of classes. For example, the switch statement that was performing the operations in the “normal” version of our program can be written as follows:

C#
private double Calculation(double Value1, double Value2, char Symbol)
{
        double Result = 0.00;

        switch(Symbol)
        {
        case '+':
	Result = Value1 + Value2;
	break;
        case '-':
	Result = Value1 - Value2;
	break;
        case '*':
	Result = Value1 * Value2;
	break;
        case '/':
	Result = Value1 / Value2;
	break;
        }

        return Result;
}

private void button1_Click(object sender, System.EventArgs e)
{
        double Operand1, Operand2;
        double Result = 0.00;
        char Operator;

        try 
        {
	Operand1 = double.Parse(this.txtNumber1.Text);
	Operator = char.Parse(this.txtOperator.Text);
	Operand2 = double.Parse(this.txtNumber2.Text);

	if( (Operator != '+') &&
                    (Operator != '-') && 
	    (Operator != '*') && 
	    (Operator != '/') )
	        throw new Exception(Operator.ToString());

	if( Operator == '/' )
	        if( Operand2 == 0 )
	                throw new DivideByZeroException("Division by zero is not allowed");
	Result = Operand1 / Operand2;
	this.txtResult.Text = Result.ToString();
				
	Result = Calculation(Operand1, Operand2, Operator);
	this.txtResult.Text = Result.ToString();
        }
        catch(FormatException)
        {
	MessageBox.Show("You type an invalid number. Please correct it");
        }
        catch(DivideByZeroException ex)
        {
	MessageBox.Show(ex.Message);
        }
        catch(Exception ex)
        {
	MessageBox.Show("Operation Error: " + ex.Message + " is not a valid operator");
        }
}

This is an example of running the program:

You can still use regular methods along with methods that handle exceptions. Here is an example:

C#
private double Addition(double Value1, double Value2)
{
	double Result;
		Result = Value1 + Value2;
	return Result;
}

private double Subtraction(double Value1, double Value2)
{
	double Result;

	Result = Value1 - Value2;
	return Result;
}

private double Multiplication(double Value1, double Value2)
{
	double Result;

	Result = Value1 * Value2;
	return Result;
}

private double Division(double Value1, double Value2)
{
	double Result;

	Result = Value1 / Value2;
	return Result;
}

private void button1_Click(object sender, System.EventArgs e)
{
	double Operand1, Operand2;
	double Result = 0.00;
	char Operator;

	try 
	{
		Operand1 = double.Parse(this.txtNumber1.Text);
		Operator = char.Parse(this.txtOperator.Text);
		Operand2 = double.Parse(this.txtNumber2.Text);

		if( Operator != '+' && Operator != '-' && 
			Operator != '*' && Operator != '/' )
			throw new Exception(Operator.ToString());

	    if( Operator == '/' )
		if( Operand2 == 0 )
		    throw new DivideByZeroException("Division by zero is not allowed");
				
		switch(Operator)
		{
			case '+':
				Result = Addition(Operand1, Operand2);
				break;
			case '-':
				Result = Subtraction(Operand1, Operand2);
				break;
			case '*':
				Result = Multiplication(Operand1, Operand2);
				break;
			case '/':
				Result = Division(Operand1, Operand2);
				break;
		}

		this.txtResult.Text = Result.ToString();
	}
	catch(FormatException)
	{
		MessageBox.Show("You type an invalid number. Please correct it");
	}
	catch(DivideByZeroException ex)
	{
		MessageBox.Show(ex.Message);
	}
	catch(Exception ex)
	{
	MessageBox.Show("Operation Error: " + ex.Message + " is not a valid operator");
	}
}

As done in Main(), any method of a program can take care of its own exceptions that would occur in its body. Isolating assignments and handing them to methods is an important matter in the area of application programming. Consider the following Division method:

C#
private double Addition(double Value1, double Value2)
{
	double Result;

	Result = Value1 + Value2;
	return Result;
}

private double Subtraction(double Value1, double Value2)
{
	double Result;

	Result = Value1 - Value2;
	return Result;
}

private double Multiplication(double Value1, double Value2)
{
	double Result;

	Result = Value1 * Value2;
	return Result;
}

private double Division(double Value1, double Value2)
{
	double Result;

	try 
	{
		if( Value2 == 0 )
			throw new DivideByZeroException("Division by zero is not allowed");
				
		Result = Value1 / Value2;
		return Result;
	}
	catch(DivideByZeroException ex)
	{
		MessageBox.Show(ex.Message);
	}

	return 0.00;
}

private void button1_Click(object sender, System.EventArgs e)
{
	double Operand1, Operand2;
	double Result = 0.00;
	char Operator;

	try 
	{
		Operand1 = double.Parse(this.txtNumber1.Text);
		Operator = char.Parse(this.txtOperator.Text);
		Operand2 = double.Parse(this.txtNumber2.Text);

		if( Operator != '+' && Operator != '-' && 
			Operator != '*' && Operator != '/' )
			throw new Exception(Operator.ToString());

		switch(Operator)
		{
			case '+':
				Result = Addition(Operand1, Operand2);
				break;
			case '-':
				Result = Subtraction(Operand1, Operand2);
				break;
			case '*':
				Result = Multiplication(Operand1, Operand2);
				break;
			case '/':
				Result = Division(Operand1, Operand2);
				break;
		}

		this.txtResult.Text = Result.ToString();
	}
	catch(FormatException)
	{
		MessageBox.Show("You type an invalid number. Please correct it");
	}
	catch(Exception ex)
	{
		MessageBox.Show("Operation Error: " + ex.Message + " is not a valid operator");
	}
}

One strategy for exception handling involves using a central method to receive data and pass it to an external function. That external function then validates the data and, if an error is found, either displays a message or issues a throw, which can be caught by the calling method.

Exercises#

Geometric Calculations#

  1. Create a Windows Application named GeometricCalculations
  2. Add a class named Sphere to the project. The class must be equipped with properties that can produce the diameter, the circumference, the area, and the volume
  3. Design the form so it can take a radius value and can display the diameter, the circumference, the area, and the volume
  4. Write code that can display the results of the diameter, the circumference, the area, and the volume calculated from the Sphere class
  5. Add the tooltips to all controls on the form
  6. Create a help file that will assist the user with the application

Georgetown Cleaning Services#

  1. Open the GeorgetownCleaningServices1 application from the previous lesson
  2. Add the tooltips to all controls on the form
  3. Create a help file that will assist the user with the application

Clarksville Ice Cream#

  1. Create a Windows Application named ClarskvilleIceCream1a
  2. Design the form as follows:
  3. Add tool tips and help to the application

Home Copyright © 2008 C# Key