Exception Handling |
|
Imagine you want to write a program that requests a number from the user, multiplies the number by 2, and displays the result. The form of this program can be designed as follows:
This looks like an easy request. When it comes up, the user is asked to simply type a number. The number would then be multiplied by 2 and display the result. Imagine that a user types something that is not a valid number, such as the name of a country or somebody’s telephone number. Since this program was expecting a number and it is not prepared to multiply a string to a number, it would produce an error. Whenever the compiler is handed a task, it would try to perform the assignment. If it can’t proceed, for any reason it is not prepared for, it would cause an error. As a programmer, if you can anticipate the type of error that could occur in your program, you can catch the error yourself and deal with it by telling the compiler what to do when this type of error occurs. |
Practical Learning: Introducing Exception Handling |
|
#pragma once namespace GCS4 { . . . No Change private: /// <summary> /// Required designer variable. /// </summary> System::ComponentModel::Container * components; // Order Information String *CustomerName; String *mm, *dd, *yyyy; // Quantities of items int NumberOfShirts; int NumberOfPants; int NumberOfDresses; // Price of items double PriceOneShirt, PriceAPairOfPants, PriceOneDress; // Each of these sub totals will be used for cleaning items double SubTotalShirts, SubTotalPants, SubTotalDresses; // Values used to process an order double TaxRate; double TotalOrder, TaxAmount, SalesTotal; /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> void InitializeComponent(void) { . . . No Change } private: System::Void btnProcess_Click(System::Object * sender, System::EventArgs * e) { if( this->btnProcess->Text->Equals(S"Process") ) { // Request order information from the user CustomerName = this->txtCustomer1->Text; mm = this->txtMM->Text; dd = this->txtDD->Text; yyyy = this->txtYYYY->Text; // Request the quantity of each category of items // Number of Shirts NumberOfShirts = this->txtQtyShirts->Text->ToInt32(0); // Number of Pants NumberOfPants = this->txtQtyPants->Text->ToInt32(0); // Number of Dresses NumberOfDresses = this->txtQtyDresses->Text->ToInt32(0); // Unit Prices of items PriceOneShirt = this->txtUnitPriceShirts->Text->ToDouble(0); PriceAPairOfPants = this->txtUnitPricePants->Text->ToDouble(0); PriceOneDress = this->txtUnitPriceDresses->Text->ToDouble(0); // Perform the necessary calculations SubTotalShirts = NumberOfShirts * PriceOneShirt; SubTotalPants = NumberOfPants * PriceAPairOfPants; SubTotalDresses = NumberOfDresses * PriceOneDress; this->txtSubTotalShirts->Text = SubTotalShirts.ToString("C"); this->txtSubTotalPants->Text = SubTotalPants.ToString("C"); this->txtSubTotalDresses->Text = SubTotalDresses.ToString("C"); // Calculate the "temporary" total of the order TotalOrder = SubTotalShirts + SubTotalPants + SubTotalDresses; // Display the receipt this->txtCustomer2->Text = CustomerName; this->txtOrderDate->Text = String::Concat(mm, S"/", dd, S"/", yyyy); this->txtTotalOrder->Text = TotalOrder.ToString("C"); this->Height = 416; this->btnProcess->Text = "Reset"; } else { this->Height = 240; this->txtCustomer1->Text = ""; this->txtMM->Text = "1"; this->txtDD->Text = "1"; this->txtYYYY->Text = "1970"; this->txtQtyShirts->Text = "0"; this->txtQtyPants->Text = "0"; this->txtQtyDresses->Text = "0"; this->txtSubTotalShirts->Text = "$0.00"; this->txtSubTotalPants->Text = "$0.00"; this->txtSubTotalDresses->Text = "$0.00"; this->btnProcess->Text = "Process"; } } }; } |
private: System::Void btnTax_Click(System::Object * sender, System::EventArgs * e) { // Get the tax rate TaxRate = this->txtTaxRate->Text->ToDouble(0) / 100; // 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("C"); this->txtNetPrice->Text = SalesTotal.ToString("C"); } |
private: System::Void btnDifference_Click(System::Object * sender, System::EventArgs * e) { double AmountTended, Difference; // Request money for the order AmountTended = this->txtAmountTended->Text->ToDouble(0); // Calculate the difference owed to the customer // or that the customer still owes to the store Difference = AmountTended - SalesTotal; this->txtDifference->Text = Difference.ToString("C"); } |
Exceptional Behaviors |
An exception is an unusual situation that could occur in your program. As a programmer, you should anticipate any abnormal behavior that could be caused by the user entering wrong information that could otherwise lead to unpredictable results. The ability to deal with a program’s eventual abnormal behavior is called exception handling. The C/C++ language provides four main keywords to handle an exception. At this time, we will review two of them: try and catch. Later on, one more keyword, throw, will be reviewed. In another lesson, we will introduce the last keyword, __finally.
|
Practical Learning: Introducing Vague Exceptions |
private: System::Void btnProcess_Click(System::Object * sender, System::EventArgs * e) { if( this->btnProcess->Text->Equals(S"Process") ) { // Request order information from the user CustomerName = this->txtCustomer1->Text; mm = this->txtMM->Text; dd = this->txtDD->Text; yyyy = this->txtYYYY->Text; // Request the quantity of each category of items try { // Number of Shirts NumberOfShirts = this->txtQtyShirts->Text->ToInt32(0); } catch(...) { } try { // Number of Pants NumberOfPants = this->txtQtyPants->Text->ToInt32(0); } catch(...) { } try { // Number of Dresses NumberOfDresses = this->txtQtyDresses->Text->ToInt32(0); } catch(...) { } // Unit Prices of items PriceOneShirt = this->txtUnitPriceShirts->Text->ToDouble(0); PriceAPairOfPants = this->txtUnitPricePants->Text->ToDouble(0); PriceOneDress = this->txtUnitPriceDresses->Text->ToDouble(0); // Perform the necessary calculations SubTotalShirts = NumberOfShirts * PriceOneShirt; SubTotalPants = NumberOfPants * PriceAPairOfPants; SubTotalDresses = NumberOfDresses * PriceOneDress; this->txtSubTotalShirts->Text = SubTotalShirts.ToString("C"); this->txtSubTotalPants->Text = SubTotalPants.ToString("C"); this->txtSubTotalDresses->Text = SubTotalDresses.ToString("C"); // Calculate the "temporary" total of the order TotalOrder = SubTotalShirts + SubTotalPants + SubTotalDresses; // Display the receipt this->txtCustomer2->Text = CustomerName; this->txtOrderDate->Text = String::Concat(mm, S"/", dd, S"/", yyyy); this->txtTotalOrder->Text = TotalOrder.ToString("C"); this->Height = 416; this->btnProcess->Text = "Reset"; } else { this->Height = 240; this->txtCustomer1->Text = ""; this->txtMM->Text = "1"; this->txtDD->Text = "1"; this->txtYYYY->Text = "1970"; this->txtQtyShirts->Text = "0"; this->txtQtyPants->Text = "0"; this->txtQtyDresses->Text = "0"; this->txtSubTotalShirts->Text = "$0.00"; this->txtSubTotalPants->Text = "$0.00"; this->txtSubTotalDresses->Text = "$0.00"; this->btnProcess->Text = "Process"; } } private: System::Void btnTax_Click(System::Object * sender, System::EventArgs * e) { try { // Get the tax rate TaxRate = this->txtTaxRate->Text->ToDouble(0) / 100; } catch(...) { } // 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("C"); this->txtNetPrice->Text = SalesTotal.ToString("C"); } private: System::Void btnDifference_Click(System::Object * sender, System::EventArgs * e) { double AmountTended, Difference; try { // Request money for the order AmountTended = this->txtAmountTended->Text->ToDouble(0); } catch(...) { } // Calculate the difference owed to the customer // or that the customer still owes to the store Difference = AmountTended - SalesTotal; this->txtDifference->Text = Difference.ToString("C"); } |
Exceptions and Custom Messages |
As mentioned already, if an error occurs when processing the program in the try section, the compiler transfers the processing to the next catch section. You can then use the catch section to deal with the error. At a minimum, you can display a message to inform the user. Here is an example: |
private: System::Void button1_Click(System::Object * sender, System::EventArgs * e) { double number, result; try { number = textBox1->Text->ToDouble(0); result = number * 2; textBox2->Text = result.ToString(); } catch(...) { MessageBox::Show(S"Invalid Number"); } } |
Of course, your message may not be particularly clear but this time, the program will not crash. In the next sections, we will learn better ways of dealing with the errors and the messages. |
Practical Learning: Displaying Custom Messages |
private: System::Void btnProcess_Click(System::Object * sender, System::EventArgs * e) { if( this->btnProcess->Text->Equals(S"Process") ) { // Request order information from the user CustomerName = this->txtCustomer1->Text; mm = this->txtMM->Text; dd = this->txtDD->Text; yyyy = this->txtYYYY->Text; // Request the quantity of each category of items try { // Number of Shirts NumberOfShirts = this->txtQtyShirts->Text->ToInt32(0); } catch(...) { MessageBox::Show(S"The value you typed for the number of " S"shirts is not a valid number." S"\nPlease enter a natural number such as 2 or 24 or even 248"); } try { // Number of Pants NumberOfPants = this->txtQtyPants->Text->ToInt32(0); } catch(...) { MessageBox::Show(S"The value you typed for the number of " S"pair or pants is not a valid number." S"\nPlease enter a natural number such as 2 or 24 or even 248"); } try { // Number of Dresses NumberOfDresses = this->txtQtyDresses->Text->ToInt32(0); } catch(...) { MessageBox::Show(S"The value you typed for the number of " S"dresses is not a valid number." S"\nPlease enter a natural number such as 2 or 24 or even 248"); } // Unit Prices of items try { PriceOneShirt = this->txtUnitPriceShirts->Text->ToDouble(0); } catch(...) { MessageBox::Show(S"The value you entered for the unit price of " S"a shirt is not a recognizable currency amount." S"\nOnly natural or decimal numbers are allowed. " S"Please consult the management to know the valid prices."); } try { PriceAPairOfPants = this->txtUnitPricePants->Text->ToDouble(0); } catch(...) { MessageBox::Show(S"The value you entered for the unit price of " S"a pair of pants is not a recognizable currency amount." S"\nOnly natural or decimal numbers are allowed. " S"You can consult the management to find out about " S"the allowable prices."); } try { PriceOneDress = this->txtUnitPriceDresses->Text->ToDouble(0); } catch(...) { MessageBox::Show(S"The value you entered for the unit price of " S"a dress is not a valid amount." S"\nYou must enter only a natural or a decimal number. " S"For more information, please consult the management to get " S"the right prices."); } // Perform the necessary calculations SubTotalShirts = NumberOfShirts * PriceOneShirt; SubTotalPants = NumberOfPants * PriceAPairOfPants; SubTotalDresses = NumberOfDresses * PriceOneDress; this->txtSubTotalShirts->Text = SubTotalShirts.ToString("C"); this->txtSubTotalPants->Text = SubTotalPants.ToString("C"); this->txtSubTotalDresses->Text = SubTotalDresses.ToString("C"); // Calculate the "temporary" total of the order TotalOrder = SubTotalShirts + SubTotalPants + SubTotalDresses; // Display the receipt this->txtCustomer2->Text = CustomerName; this->txtOrderDate->Text = String::Concat(mm, S"/", dd, S"/", yyyy); this->txtTotalOrder->Text = TotalOrder.ToString("C"); this->Height = 416; this->btnProcess->Text = "Reset"; } else { this->Height = 240; this->txtCustomer1->Text = ""; this->txtMM->Text = "1"; this->txtDD->Text = "1"; this->txtYYYY->Text = "1970"; this->txtQtyShirts->Text = "0"; this->txtQtyPants->Text = "0"; this->txtQtyDresses->Text = "0"; this->txtSubTotalShirts->Text = "$0.00"; this->txtSubTotalPants->Text = "$0.00"; this->txtSubTotalDresses->Text = "$0.00"; this->btnProcess->Text = "Process"; } } private: System::Void btnTax_Click(System::Object * sender, System::EventArgs * e) { try { // Get the tax rate TaxRate = this->txtTaxRate->Text->ToDouble(0) / 100; } catch(...) { MessageBox::Show(S"The value you entered is not recognized as a valid tax rate." S"\nA valid tax rate is a value between 0 and 100.00" S"\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("C"); this->txtNetPrice->Text = SalesTotal.ToString("C"); } private: System::Void btnDifference_Click(System::Object * sender, System::EventArgs * e) { double AmountTended, Difference; try { // Request money for the order AmountTended = this->txtAmountTended->Text->ToDouble(0); } catch(...) { MessageBox::Show(S"The value you entered for the amount tended is not valid. " S"Only natural or decimal numbers are allowed." S"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("C"); } |
Exceptions in the .NET Framework |
The Exception Class |
With C/C++, you can create any exception of your choice, including numeric or strings. So far, to handle exceptions, we were passing three periods to the catch clause. The three periods are telling the compiler that we know that an error is likely to occur but we don't know what type of error it would be. Therefore, the three periods are used for lack of more information. To customize exception handling, you can even create your own class(es). Most libraries such as Borland's VCL and Microsoft's MFC also ship with their own classes to handle exceptions. Even the Win32 library provides its type of mechanism to handle errors. To support exception handling, the .NET Framework provides a special class called Exception. Once the compiler encounters an error, the Exception class allows you to identify the type of error and take an appropriate action. Exception mostly serves as the general class of exceptions. Based on this, in a Visual C++ .NET application, instead of the three periods, you can pass an Exception pointer to the catch clause. Here is an example: private: System::Void button1_Click(System::Object * sender, System::EventArgs * e) { double number, result; try { number = textBox1->Text->ToDouble(0); result = number * 2; textBox2->Text = result.ToString(); } catch(Exception *e) { MessageBox::Show(S"Invalid Number"); } } Passing an Exception argument to catch is still a general way to catch an unknown but likely exception. Anticipating various types of problems that can occur in a program, Microsoft derived various classes from Exception to make this issue friendlier. As a result, almost any type of exception you may encounter already has a class created to deal with it. Therefore, when your program faces an exception, you can easily identify the type of error. There are so many exception classes that we cannot study or review them all. The solution we will use is to introduce or review a class when we meet its type of error.
When an exception occurs in the try section, code compilation is transferred to the catch section. If you declare the exception as an Exception type, this class will identify the error. One of the properties of the Exception class is called Message. This property contains a string that describes the type of error that occurred. You can then use this Exception::Message property to display an error message if you want. Here is an example:
As you can see, one of the strengths of the Exception::Message property is that it gives you a good indication of the type of problem that occurred. Sometimes, the message provided by the Exception class may not appear explicit enough. In fact, you may not want to show it to the user since, as in this case, the user may not understand what the expression "correct format" in this context means and why it is being used. As an alternative, you can create your own message and display it to the user. Here is an example:
You can also combine the Exception::Message message and your own message:
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 mention the few that we will regularly use in our applications. There are two main ways you can use one of the classes of the .NET Framework. If you know for sure that a particular exception will be produced, pass its pointer to a catch() clause but you don't have to name the pointer: you just have to indicate that the class is passed as a pointer. Then, in the catch() section, display a custom message. The second option you have consists of using the throw keyword. From now on, we will try to always indicate the type of exception that could be thrown if something goes wrong in a program.
Everything the user types into a control 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 the word "throw") an error. The error is of from the FormatException class. Here is a program that deals with a FormatException exception:
|
Practical Learning: Using the FormatException Class |
private: System::Void btnProcess_Click(System::Object * sender, System::EventArgs * e) { if( this->btnProcess->Text->Equals(S"Process") ) { . . . No Change // Request the quantity of each category of items try { // Number of Shirts NumberOfShirts = this->txtQtyShirts->Text->ToInt32(0); } catch(FormatException *) { MessageBox::Show(S"The value you typed for the number of " S"shirts is not a valid number." S"\nPlease enter a natural number such as 2 or 24 or even 248"); } try { // Number of Pants NumberOfPants = this->txtQtyPants->Text->ToInt32(0); } catch(FormatException *) { MessageBox::Show(S"The value you typed for the number of " S"pair or pants is not a valid number." S"\nPlease enter a natural number such as 2 or 24 or even 248"); } try { // Number of Dresses NumberOfDresses = this->txtQtyDresses->Text->ToInt32(0); } catch(FormatException *) { MessageBox::Show(S"The value you typed for the number of " S"dresses is not a valid number." S"\nPlease enter a natural number such as 2 or 24 or even 248"); } // Unit Prices of items try { PriceOneShirt = this->txtUnitPriceShirts->Text->ToDouble(0); } catch(FormatException *) { MessageBox::Show(S"The value you entered for the unit price of " S"a shirt is not a recognizable currency amount." S"\nOnly natural or decimal numbers are allowed. " S"Please consult the management to know the valid prices."); } try { PriceAPairOfPants = this->txtUnitPricePants->Text->ToDouble(0); } catch(FormatException *) { MessageBox::Show(S"The value you entered for the unit price of " S"a pair of pants is not a recognizable currency amount." S"\nOnly natural or decimal numbers are allowed. " S"You can consult the management to find out about " S"the allowable prices."); } try { PriceOneDress = this->txtUnitPriceDresses->Text->ToDouble(0); } catch(FormatException *) { MessageBox::Show(S"The value you entered for the unit price of " S"a dress is not a valid amount." S"\nYou must enter only a natural or a decimal number. " S"For more information, please consult the management to get " S"the right prices."); } . . . No Change } private: System::Void btnTax_Click(System::Object * sender, System::EventArgs * e) { try { // Get the tax rate TaxRate = this->txtTaxRate->Text->ToDouble(0) / 100; } catch(FormatException *) { MessageBox::Show(S"The value you entered is not recognized as a valid tax rate." S"\nA valid tax rate is a value between 0 and 100.00" S"\nPlease try again."); } . . . No Change } private: System::Void btnDifference_Click(System::Object * sender, System::EventArgs * e) { double AmountTended, Difference; try { // Request money for the order AmountTended = this->txtAmountTended->Text->ToDouble(0); } catch(FormatException *) { MessageBox::Show(S"The value you entered for the amount tended is not valid. " S"Only natural or decimal numbers are allowed." S"Please try again."); } . . . No Change } |
The OverflowException Exception |
A computer application receives, processes, and produces values on a regular basis as the program is running. To better manage these values, 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, 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:
When a value beyond the allowable range is asked to be stored in memory, the compiler produces 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.
Once again, we know that a value can be 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 produces a FormatException exception as we saw above. Other classes such as DateTime also use a Parse() method to scan the value submitted to them. 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:
If the user types a value that cannot be converted into a valid date, the compiler produces 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 produced. |
Practical Learning: Using an ArgumentOutOfRangeException Exception |
#pragma once namespace GCS1 { . . . No Change private: /// <summary> /// Required designer variable. /// </summary> System::ComponentModel::Container * components; // Order Information String *CustomerName; DateTime OrderDate; // Quantities of items int NumberOfShirts; int NumberOfPants; int NumberOfDresses; // Price of items double PriceOneShirt, PriceAPairOfPants, PriceOneDress; // Each of these sub totals will be used for cleaning items double SubTotalShirts, SubTotalPants, SubTotalDresses; // Values used to process an order double TaxRate; double TotalOrder, TaxAmount, SalesTotal; /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> void InitializeComponent(void) { . . . No Change } private: System::Void btnProcess_Click(System::Object * sender, System::EventArgs * e) { if( this->btnProcess->Text->Equals(S"Process") ) { // Request order information from the user CustomerName = this->txtCustomer1->Text; try { int mm, dd, yyyy; mm = this->txtMM->Text->ToInt32(0); dd = this->txtDD->Text->ToInt32(0); yyyy = this->txtYYYY->Text->ToInt32(0); OrderDate = DateTime(yyyy, mm, dd); } catch(ArgumentOutOfRangeException *) { MessageBox::Show(S"The date you entered is not valid - Please try again!"); } // Request the quantity of each category of items try { // Number of Shirts NumberOfShirts = this->txtQtyShirts->Text->ToInt32(0); } catch(FormatException *) { MessageBox::Show(S"The value you typed for the number of " S"shirts is not a valid number." S"\nPlease enter a natural number such as 2 or 24 or even 248"); } . . . No Change // Display the receipt this->txtCustomer2->Text = CustomerName; this->txtOrderDate->Text = OrderDate.ToString(S"D"); this->txtTotalOrder->Text = TotalOrder.ToString(S"C"); this->Height = 416; this->btnProcess->Text = S"Reset"; } else { this->Height = 240; this->txtCustomer1->Text = S""; this->txtMM->Text = S"1"; this->txtDD->Text = S"1"; this->txtYYYY->Text = S"1970"; this->txtQtyShirts->Text = S"0"; this->txtQtyPants->Text = S"0"; this->txtQtyDresses->Text = S"0"; this->txtSubTotalShirts->Text = S"$0.00"; this->txtSubTotalPants->Text = "$0.00"; this->txtSubTotalDresses->Text = S"$0.00"; this->btnProcess->Text = S"Process"; } } |
DivideByZeroException |
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 computer processor itself. It is addressed by the operating system at its 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 produces a DivideByZeroException exception. We will use it later. |
Techniques of Using Exceptions |
Throwing an Exception |
As mentioned above, the Exception class is equipped with a Message property that carries 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: public: Exception(String *message); To use it, in the section where you are anticipating the error, type the throw keyword followed by a new operator and an instance of the Exception class using the constructor that takes a string. Here is an example: |
private: System::Void button1_Click(System::Object * sender, System::EventArgs * e) { double Operand1, Operand2; double Result = 0.00; String *Operator; try { Operand1 = this->txtNumber1->Text->ToDouble(0); Operator = this->txtOperator->Text; Operand2 = this->txtNumber2->Text->ToDouble(0); if( !Operator->Equals(S"+") && !Operator->Equals(S"-") && !Operator->Equals(S"*") && !Operator->Equals(S"/") ) throw new Exception(Operator); if( Operator->Equals(S"+") ) Result = Operand1 + Operand2; else if( Operator->Equals(S"-") ) Result = Operand1 - Operand2; else if(Operator->Equals(S"*") ) Result = Operand1 * Operand2; else if( Operator->Equals(S"/") ) Result = Operand1 / Operand2; else MessageBox::Show(S"Bad Operation"); this->txtResult->Text = Result.ToString(); } catch(Exception *ex) { MessageBox::Show(String::Concat(S"Operation Error: ", ex->Message, S" is not a valid operator")); } } |
Catching Various Exceptions |
In the above examples, when we anticipated some type of problem, we instructed the compiler to use our default catch section. We left it up to the compiler to find out when there was a problem and we provided a catch section to deal with it. A method with numerous or complex operations and requests can also produce different types of errors. With such a type of program, you should be able to face different problems and deal with them individually, each by its own kind. To do this, you can create different catch sections, each made for a particular error. The formula used would be: try { // Code to Try } catch(Arg1) { // One Exception } catch(Arg2) { // Another Exception } The compiler would proceed in a top-down:
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: |
private: System::Void button1_Click(System::Object * sender, System::EventArgs * e) { double Operand1, Operand2; double Result = 0.00; String *Operator; try { Operand1 = this->txtNumber1->Text->ToDouble(0); Operator = this->txtOperator->Text; Operand2 = this->txtNumber2->Text->ToDouble(0); if( !Operator->Equals(S"+") && !Operator->Equals(S"-") && !Operator->Equals(S"*") && !Operator->Equals(S"/") ) throw new Exception(Operator); if( Operator->Equals(S"+") ) Result = Operand1 + Operand2; else if( Operator->Equals(S"-") ) Result = Operand1 - Operand2; else if(Operator->Equals(S"*") ) Result = Operand1 * Operand2; else if( Operator->Equals(S"/") ) Result = Operand1 / Operand2; else MessageBox::Show(S"Bad Operation"); this->txtResult->Text = Result.ToString(); } catch(FormatException *) { MessageBox::Show(S"You typed an invalid number. Please correct it"); } catch(Exception *ex) { MessageBox::Show(String::Concat(S"Operation Error: ", ex->Message, S" 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 catch(...) block. Therefore, if you write various catch blocks, the one that takes the three periods as argument must be the last. If you provide a catch that takes an Exception class as argument, you can omit the three-period catch and provide the Exception catch as the last. Here is an example that catches two types of exceptions: |
private: System::Void button1_Click(System::Object * sender, System::EventArgs * e) { double Operand1, Operand2; double Result = 0.00; String *Operator; try { Operand1 = this->txtNumber1->Text->ToDouble(0); Operator = this->txtOperator->Text; Operand2 = this->txtNumber2->Text->ToDouble(0); if( !Operator->Equals(S"+") && !Operator->Equals(S"-") && !Operator->Equals(S"*") && !Operator->Equals(S"/") ) throw new Exception(Operator); if( Operator->Equals(S"+") ) Result = Operand1 + Operand2; else if( Operator->Equals(S"-") ) Result = Operand1 - Operand2; else if(Operator->Equals(S"*") ) Result = Operand1 * Operand2; else if( Operator->Equals(S"/") ) { if( Operand2 == 0 ) throw new DivideByZeroException(S"Division by zero is not allowed"); Result = Operand1 / Operand2; } else MessageBox::Show(S"Bad Operation"); this->txtResult->Text = Result.ToString(); } catch(FormatException *) { MessageBox::Show(S"You typed an invalid number. Please correct it"); } catch(DivideByZeroException *ex) { MessageBox::Show(ex->Message); } catch(Exception *ex) { MessageBox::Show(String::Concat(S"Operation Error: ", ex->Message, S" is not a valid operator")); } }
Practical Learning: Identifying the Thrown Exception |
private: System::Void btnProcess_Click(System::Object * sender, System::EventArgs * e) { if( this->btnProcess->Text->Equals(S"Process") ) { // Request order information from the user CustomerName = this->txtCustomer1->Text; try { int mm, dd, yyyy; mm = this->txtMM->Text->ToInt32(0); dd = this->txtDD->Text->ToInt32(0); yyyy = this->txtYYYY->Text->ToInt32(0); OrderDate = 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(String::Concat(S"Error: ", ex.Message, S"\nThe value you entered ", S"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(S"The date you entered is not valid - Please try again!"); } // Request the quantity of each category of items try { // Number of Shirts NumberOfShirts = this->txtQtyShirts->Text->ToInt32(0); } // This exception is thrown if the user typed a value that cannot // be recognized as a valid number catch(FormatException *) { MessageBox::Show(S"The value you typed for the number of " S"shirts is not a valid number." S"\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(S"The number you typed is negative but " S"we cannot accept a negative number of shirts"); } try { // Number of Pants NumberOfPants = this->txtQtyPants->Text->ToInt32(0); } catch(FormatException *) { MessageBox::Show(S"The value you typed for the number of " S"pair or pants is not a valid number." S"\nPlease enter a natural number such as 2 or 24 or even 248"); } catch(OverflowException) { MessageBox::Show(S"The number you typed is negative but " S"we cannot accept a negative number of shirts"); } try { // Number of Dresses NumberOfDresses = this->txtQtyDresses->Text->ToInt32(0); } catch(FormatException *) { MessageBox::Show(S"The value you typed for the number of " S"dresses is not a valid number." S"\nPlease enter a natural number such as 2 or 24 or even 248"); } catch(OverflowException *) { MessageBox::Show(S"The number you typed is negative but " S"we cannot accept a negative number of shirts"); } // Unit Prices of items try { PriceOneShirt = this->txtUnitPriceShirts->Text->ToDouble(0); if(PriceOneShirt < 0 ) throw new Exception(S"Negative numbers are not allowed for the price of a shirt"); } catch(FormatException *) { MessageBox::Show(S"The value you entered for the unit price of " S"a shirt is not a recognizable currency amount." S"\nOnly natural or decimal numbers are allowed. " S"Please consult the management to know the valid prices."); } catch(Exception *ex) { MessageBox::Show(ex->Message); } try { PriceAPairOfPants = this->txtUnitPricePants->Text->ToDouble(0); if( PriceAPairOfPants < 0 ) throw new Exception(S"Negative numbers are not allowed for the price of a pair of pants"); } catch(FormatException *) { MessageBox::Show(S"The value you entered for the unit price of " S"a pair of pants is not a recognizable currency amount." S"\nOnly natural or decimal numbers are allowed. " S"You can consult the management to find out about " S"the allowable prices."); } catch(Exception *ex) { MessageBox::Show(ex->Message); } try { PriceOneDress = this->txtUnitPriceDresses->Text->ToDouble(0); if( PriceOneDress < 0 ) throw new Exception(S"Negative numbers are not allowed for the price of a dress"); } catch(FormatException *) { MessageBox::Show(S"The value you entered for the unit price of " S"a dress is not a valid amount." S"\nYou must enter only a natural or a decimal number. " S"For more information, please consult the management to get " S"the right prices."); } catch(Exception *ex) { MessageBox::Show(ex->Message); } . . . No Change } private: System::Void btnTax_Click(System::Object * sender, System::EventArgs * e) { try { // Get the tax rate TaxRate = this->txtTaxRate->Text->ToDouble(0) / 100; if(PriceOneShirt < 0 ) throw new Exception(S"Negative numbers are not allowed for a tax rate"); } catch(FormatException *) { MessageBox::Show(S"The value you entered is not recognized as a valid tax rate." S"\nA valid tax rate is a value between 0 and 100.00" S"\nPlease try again."); } catch(Exception *ex) { MessageBox::Show(ex->Message); } . . . No Change this->txtTaxAmount->Text = TaxAmount.ToString("C"); this->txtNetPrice->Text = SalesTotal.ToString("C"); } |
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 clause(s). To effectively handle the exception, make sure you include an appropriate throw in the try block. Here is an example: |
private: System::Void button1_Click(System::Object * sender, System::EventArgs * e) { double Operand1, Operand2; double Result = 0.00; String *Operator; try { Operand1 = this->txtNumber1->Text->ToDouble(0); Operator = this->txtOperator->Text; Operand2 = this->txtNumber2->Text->ToDouble(0); if( !Operator->Equals(S"+") && !Operator->Equals(S"-") && !Operator->Equals(S"*") && !Operator->Equals(S"/") ) throw new Exception(Operator); if( Operator->Equals(S"+") ) { Result = Operand1 + Operand2; this->txtResult->Text = Result.ToString(); } else if( Operator->Equals(S"-") ) { Result = Operand1 - Operand2; this->txtResult->Text = Result.ToString(); } else if(Operator->Equals(S"*") ) { Result = Operand1 * Operand2; this->txtResult->Text = Result.ToString(); } else if( Operator->Equals(S"/") ) { try { if( Operand2 == 0 ) throw new DivideByZeroException(S"Division by zero is not allowed"); Result = Operand1 / Operand2; this->txtResult->Text = Result.ToString(); } catch(DivideByZeroException *ex) { MessageBox::Show(ex->Message); } } else MessageBox::Show(S"Bad Operation"); } catch(FormatException *) { MessageBox::Show(S"You typed an invalid number. Please correct it"); } catch(Exception *ex) { MessageBox::Show(String::Concat(S"Operation Error: ", ex->Message, S" is not a valid operator")); } }
|
||
Home | Copyright © 2004-2010 FunctionX, Inc. | |
|