Introduction to Exception Handling
Introduction to Exception Handling
Introduction to Exceptions
Overview
During the execution of a program, the computer will face two types of situations: those it is prepared to deal with and those it is not. Imagine you write a program that requests a number from the user:
using System; class Geometry { static int Main() { double side; Console.WriteLine("Square Processing"); Console.Write("Enter Side: "); side = double.Parse(Console.ReadLine()); Console.WriteLine("Square Characteristics"); Console.WriteLine("Side: {0}", side); Console.WriteLine("Perimeter: {0}", side * 4); return 0; } }
This is a classic easy program. When it comes up, the user is asked to simply type a number. The number would then be multiplied by 4 and the result is displayed. 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 not know what to do. The only alternative the compiler would have is to send the problem to the operating system, hoping that the OS would know what to do. What actually happens is that, whenever the compiler is handed a task, it would try to perform the assignment. If it cannot perform the assignment, for any reason it is not prepared for, it would produce an error. As a programmer, if you can anticipate the type of error that could occur in your program, you can identify the error yourself and deal with it by telling the compiler what to do when an error occurs.
Practical Learning: Introducing Exception Handling
using static System.Console; public class OrderProcessing { public static int Main() { // Price of items const double PriceOneShirt = 1.25; const double PriceAPairOfPants = 2.15; const double PriceOtherItem = 3.45; const double TaxRate = 5.75; // 5.75% // Basic information about an order string customerName, homePhone; string orderDate, orderTime; // Unsigned numbers to represent cleaning items int numberOfShirts, numberOfPants, numberOfOtherItems; // Each of these sub totals will be used for cleaning items double subTotalShirts, subTotalPants, subTotalOtherItems; // Values used to process an order double totalOrder, taxAmount, salesTotal; double amountTended, moneyChange; Title = "Georgetown Dry Cleaning Services"; WriteLine("==============================================="); WriteLine("-/- Georgetown Dry Cleaning Services -/-"); WriteLine("=============================================="); // Request order information from the user Write("Enter Customer Name: "); customerName = ReadLine(); Write("Enter Customer Phone: "); homePhone = ReadLine(); Write("Enter the order date (mm/dd/yyyy): "); orderDate = ReadLine(); Write("Enter the order time (hh:mm AM/PM): "); orderTime = ReadLine(); // Request the quantity of each category of items Write("Number of Shirts: "); string strShirts = ReadLine(); numberOfShirts = int.Parse(strShirts); Write("Number of Pants: "); string strPants = ReadLine(); numberOfPants = int.Parse(strPants); Write("Number of Other Items: "); string strDresses = ReadLine(); numberOfOtherItems = int.Parse(strDresses); // Perform the necessary calculations subTotalShirts = numberOfShirts * PriceOneShirt; subTotalPants = numberOfPants * PriceAPairOfPants; subTotalOtherItems = numberOfOtherItems * PriceOtherItem; // Calculate the "temporary" total of the order totalOrder = subTotalShirts + subTotalPants + subTotalOtherItems; // Calculate the tax amount using a constant rate taxAmount = totalOrder * TaxRate / 100.00; // Add the tax amount to the total order salesTotal = totalOrder + taxAmount; WriteLine("-----------------------------------------"); // Communicate the total to the user... WriteLine("The Total order is: {0:C}", salesTotal); // and request money for the order Write("Amount Tended? "); amountTended = double.Parse(ReadLine()); // Calculate the difference owed to the customer // or that the customer still owes to the store moneyChange = amountTended - salesTotal; Clear(); Title = "Georgetown Dry Cleaning Services"; // Display the receipt WriteLine("========================================="); WriteLine("-/- Georgetown Dry Cleaning Services -/-"); WriteLine("========================================="); WriteLine("Customer: {0}", customerName); WriteLine("Home Phone: {0}", homePhone); WriteLine("Order Date: {0}", orderDate); WriteLine("Order Time: {0}", orderTime); WriteLine("-----------------------------------------"); WriteLine("Item Type Qty Unit/Price Sub-Total"); WriteLine("-----------------------------------------"); WriteLine("Shirts{0,9} {1:C} {2:C}", numberOfShirts, PriceOneShirt, subTotalShirts); WriteLine("Pants{0,10} {1:C} {2:C}", numberOfPants, PriceAPairOfPants, subTotalPants); WriteLine("Other Items{0,4} {1:C} {2:C}", numberOfOtherItems, PriceOtherItem, subTotalOtherItems); WriteLine("-----------------------------------------"); WriteLine("Total Order: {0:C,20}", totalOrder.ToString()); WriteLine("Tax Rate: {0:P}", TaxRate / 100); WriteLine("Tax Amount: {0:C}", taxAmount); WriteLine("Net Price: {0:C}", salesTotal); WriteLine("-----------------------------------------"); WriteLine("Amount Tended: {0:C}", amountTended); WriteLine("Difference: {0:C}", moneyChange); WriteLine("========================================="); return 0; } }
=============================================== -/- Georgetown Dry Cleaning Services -/- ============================================== Enter Customer Name: Peter Moonstruck Enter Customer Phone: (301) 728-8830 Enter the order date (mm/dd/yyyy): 04/22/2019 Enter the order time (hh:mm AM/PM): 08:46 Number of Shirts: 5 Number of Pants: 2 Number of Other Items: 3
===============================================
-/- Georgetown Dry Cleaning Services -/-
==============================================
Enter Customer Name: Peter Moonstruck
Enter Customer Phone: (301) 728-8830
Enter the order date (mm/dd/yyyy): 04/22/2019
Enter the order time (hh:mm AM/PM): 08:46
Number of Shirts: 5
Number of Pants: 2
Number of Other Items: 3
-----------------------------------------
The Total order is: $22.10
Amount Tended? 30
========================================= -/- Georgetown Dry Cleaning Services -/- ========================================= Customer: Peter Moonstruck Home Phone: (301) 728-8830 Order Date: 04/22/2019 Order Time: 08:46 ----------------------------------------- Item Type Qty Unit/Price Sub-Total ----------------------------------------- Shirts 5 $1.25 $6.25 Pants 2 $2.15 $4.30 Other Items 3 $3.45 $10.35 ----------------------------------------- Total Order: 20.9 Tax Rate: 5.75 % Tax Amount: $1.20 Net Price: $22.10 ----------------------------------------- Amount Tended: $30.00 Difference: $7.90 ========================================= Press any key to continue . . .
=============================================== -/- Georgetown Dry Cleaning Services -/- ============================================== Enter Customer Name: Ricardo Sanchez Enter Customer Phone: (443) 142-3048 Enter the order date (mm/dd/yyyy): 06/22/2019 Enter the order time (hh:mm AM/PM): 11:27 AM Number of Shirts: five
An exception is an unusual situation that could occur in your application. 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 behaviors is called exception handling. C# provides three keywords to handle an exception.
using System;
class Geometry
{
static int Main()
{
double side;
Console.WriteLine("Square Processing");
try
{
Console.Write("Enter Side: ");
side = double.Parse(Console.ReadLine());
Console.WriteLine("Square Characteristics");
Console.WriteLine("Side: {0}", side);
Console.WriteLine("Perimeter: {0}", side * 4);
}
return 0;
}
}
In a try block, if you want to involve a variable in an expression, that variable must first hold a value. You initialize such a variable when declaring it. Here is an example:
using System;
public class Geometry
{
static int Main()
{
double side = 0.00;
Console.WriteLine("Square Processing");
try
{
Console.Write("Enter Side: ");
side = double.Parse(Console.ReadLine());
Console.WriteLine("Square Characteristics");
Console.WriteLine("Side: {0}", side);
Console.WriteLine("Perimeter: {0}", side * 4);
}
return 0;
}
}
You can also specify a value for the variable inside the try section. Here is an example:
using System; public class Geometry { static int Main() { double side; Console.WriteLine("Square Processing"); try { side = 0.00; Console.Write("Enter Side: "); side = double.Parse(Console.ReadLine()); Console.WriteLine("Square Characteristics"); Console.WriteLine("Side: {0}", side); Console.WriteLine("Perimeter: {0}", side * 4); } return 0; } }
The rule is that the variable must hold a non-null value before it gets involved in an expression.
This section always follows the try section. There must
not be any code between the try's closing bracket and the catch
section. The catch keyword is required and follows the try
section.
Combined with the try block, the primary formula to handle an exception is:
try { // Try the program flow } catch { // Catch the exception }A program that includes a catch section would appear as follows:
using System;
public class Exercise
{
static int Main()
{
double number = 0.00;
try
{
Console.Write("Type a number: ");
Number = double.Parse(Console.ReadLine());
Console.WriteLine("{0} * 2 = {1}", number, number * 2);
}
catch
{
}
return 0;
}
}
Practical Learning: Introducing Vague Exceptions
using static System.Console; public class OrderProcessing { public static int Main() { // Price of items const double PriceOneShirt = 1.25; const double PriceAPairOfPants = 2.15; const double PriceOtherItem = 3.45; const double TaxRate = 5.75; // 5.75% // Basic information about an order string customerName, homePhone; string orderDate, orderTime; // Unsigned numbers to represent cleaning items int numberOfShirts = 0, numberOfPants = 0, numberOfOtherItems = 0; // Each of these sub totals will be used for cleaning items double subTotalShirts, subTotalPants, subTotalOtherItems; // Values used to process an order double totalOrder, taxAmount, salesTotal; double amountTended = 0, moneyChange; Title = "Georgetown Dry Cleaning Services"; WriteLine("==============================================="); WriteLine("-/- Georgetown Dry Cleaning Services -/-"); WriteLine("=============================================="); // Request order information from the user Write("Enter Customer Name: "); customerName = ReadLine(); Write("Enter Customer Phone: "); homePhone = ReadLine(); Write("Enter the order date (mm/dd/yyyy): "); orderDate = ReadLine(); Write("Enter the order time (hh:mm AM/PM): "); orderTime = ReadLine(); // Request the quantity of each category of items try { Write("Number of Shirts: "); string strShirts = ReadLine(); numberOfShirts = int.Parse(strShirts); } catch { } try { Write("Number of Pants: "); string strPants = ReadLine(); numberOfPants = int.Parse(strPants); } catch { } try { Write("Number of Other Items: "); string strDresses = ReadLine(); numberOfOtherItems = int.Parse(strDresses); } catch { } // Perform the necessary calculations subTotalShirts = numberOfShirts * PriceOneShirt; subTotalPants = numberOfPants * PriceAPairOfPants; subTotalOtherItems = numberOfOtherItems * PriceOtherItem; // Calculate the "temporary" total of the order totalOrder = subTotalShirts + subTotalPants + subTotalOtherItems; // Calculate the tax amount using a constant rate taxAmount = totalOrder * TaxRate / 100.00; // Add the tax amount to the total order salesTotal = totalOrder + taxAmount; WriteLine("-----------------------------------------"); // Communicate the total to the user... WriteLine("The Total order is: {0:C}", salesTotal); // and request money for the order try { Write("Amount Tended? "); amountTended = double.Parse(ReadLine()); } catch { } // Calculate the difference owed to the customer // or that the customer still owes to the store moneyChange = amountTended - salesTotal; Clear(); Title = "Georgetown Dry Cleaning Services"; // Display the receipt WriteLine("========================================="); WriteLine("-/- Georgetown Dry Cleaning Services -/-"); WriteLine("========================================="); WriteLine("Customer: {0}", customerName); WriteLine("Home Phone: {0}", homePhone); WriteLine("Order Date: {0}", orderDate); WriteLine("Order Time: {0}", orderTime); WriteLine("-----------------------------------------"); WriteLine("Item Type Qty Unit/Price Sub-Total"); WriteLine("-----------------------------------------"); WriteLine("Shirts{0,9} {1:C} {2:C}", numberOfShirts, PriceOneShirt, subTotalShirts); WriteLine("Pants{0,10} {1:C} {2:C}", numberOfPants, PriceAPairOfPants, subTotalPants); WriteLine("Other Items{0,4} {1:C} {2:C}", numberOfOtherItems, PriceOtherItem, subTotalOtherItems); WriteLine("-----------------------------------------"); WriteLine("Total Order: {0:C,20}", totalOrder.ToString()); WriteLine("Tax Rate: {0:P}", TaxRate / 100); WriteLine("Tax Amount: {0:C}", taxAmount); WriteLine("Net Price: {0:C}", salesTotal); WriteLine("-----------------------------------------"); WriteLine("Amount Tended: {0:C}", amountTended); WriteLine("Difference: {0:C}", moneyChange); WriteLine("========================================="); return 0; } }
=============================================== -/- Georgetown Dry Cleaning Services -/- ============================================== Enter Customer Name: Ricardo Sanchez Enter Customer Phone: (443) 142-3048 Enter the order date (mm/dd/yyyy): 06/22/2019 Enter the order time (hh:mm AM/PM): 11:27 AM Number of Shirts: five
=============================================== -/- Georgetown Dry Cleaning Services -/- ============================================== Enter Customer Name: Ricardo Sanchez Enter Customer Phone: (443) 142-3048 Enter the order date (mm/dd/yyyy): 06/22/2019 Enter the order time (hh:mm AM/PM): 11;27 AM Number of Shirts: five Number of Pants: 3 Number of Other Items: 7 ----------------------------------------- The Total order is: $32.36 Amount Tended? 35
========================================= -/- Georgetown Dry Cleaning Services -/- ========================================= Customer: Ricardo Sanchez Home Phone: (443) 142-3048 Order Date: 06/22/2019 Order Time: 11;27 AM ----------------------------------------- Item Type Qty Unit/Price Sub-Total ----------------------------------------- Shirts 0 $1.25 $0.00 Pants 3 $2.15 $6.45 Other Items 7 $3.45 $24.15 ----------------------------------------- Total Order: 30.6 Tax Rate: 5.75 % Tax Amount: $1.76 Net Price: $32.36 ----------------------------------------- Amount Tended: $35.00 Difference: $2.64 ========================================= Press any key to continue . . .
Exceptions and Custom Messages
As mentioned already, if an error occurs when processing the program in a 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:
using System;
public class Geometry
{
static int Main()
{
double side;
Console.WriteLine("Square Processing");
try
{
Console.Write("Enter Side: ");
side = double.Parse(Console.ReadLine());
Console.WriteLine("Square Characteristics");
Console.WriteLine("Side: {0}", side);
Console.WriteLine("Perimeter: {0}", side * 4);
}
catch
{
Console.WriteLine("There was a problem with the program");
}
return 0;
}
}
Here is an error of running the program:
Square Processing Enter Side: w4 There was a problem with the program Press any key to continue . . .
Of course, this type of message is not 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
using static System.Console; public class OrderProcessing { public static int Main() { // Price of items const double PriceOneShirt = 1.25; const double PriceAPairOfPants = 2.15; const double PriceOtherItem = 3.45; const double TaxRate = 5.75; // 5.75% // Basic information about an order string customerName, homePhone; string orderDate, orderTime; // Unsigned numbers to represent cleaning items int numberOfShirts = 0, numberOfPants = 0, numberOfOtherItems = 0; // Each of these sub totals will be used for cleaning items double subTotalShirts, subTotalPants, subTotalOtherItems; // Values used to process an order double totalOrder, taxAmount, salesTotal; double amountTended = 0, moneyChange; Title = "Georgetown Dry Cleaning Services"; WriteLine("==============================================="); WriteLine("-/- Georgetown Dry Cleaning Services -/-"); WriteLine("=============================================="); // Request order information from the user Write("Enter Customer Name: "); customerName = ReadLine(); Write("Enter Customer Phone: "); homePhone = ReadLine(); Write("Enter the order date (mm/dd/yyyy): "); orderDate = ReadLine(); Write("Enter the order time (hh:mm AM/PM): "); orderTime = ReadLine(); // Request the quantity of each category of items try { Write("Number of Shirts: "); string strShirts = ReadLine(); numberOfShirts = int.Parse(strShirts); } catch { WriteLine("The value you typed for the number of " + "shirts is not a valid number."); } try { Write("Number of Pants: "); string strPants = ReadLine(); numberOfPants = int.Parse(strPants); } catch { WriteLine("The value you typed for the number of " + "pants is not a valid number."); } try { Write("Number of Other Items: "); string strDresses = ReadLine(); numberOfOtherItems = int.Parse(strDresses); } catch { WriteLine("The value you typed for the number of " + "other types of items is not a valid number."); } // Perform the necessary calculations subTotalShirts = numberOfShirts * PriceOneShirt; subTotalPants = numberOfPants * PriceAPairOfPants; subTotalOtherItems = numberOfOtherItems * PriceOtherItem; // Calculate the "temporary" total of the order totalOrder = subTotalShirts + subTotalPants + subTotalOtherItems; // Calculate the tax amount using a constant rate taxAmount = totalOrder * TaxRate / 100.00; // Add the tax amount to the total order salesTotal = totalOrder + taxAmount; WriteLine("-----------------------------------------"); // Communicate the total to the user... WriteLine("The Total order is: {0:C}", salesTotal); // and request money for the order try { Write("Amount Tended? "); amountTended = double.Parse(ReadLine()); } catch { WriteLine("You were asked to enter an amount of money but something bad happened."); } // Calculate the difference owed to the customer // or that the customer still owes to the store moneyChange = amountTended - salesTotal; Clear(); Title = "Georgetown Dry Cleaning Services"; // Display the receipt WriteLine("========================================="); WriteLine("-/- Georgetown Dry Cleaning Services -/-"); WriteLine("========================================="); WriteLine("Customer: {0}", customerName); WriteLine("Home Phone: {0}", homePhone); WriteLine("Order Date: {0}", orderDate); WriteLine("Order Time: {0}", orderTime); WriteLine("-----------------------------------------"); WriteLine("Item Type Qty Unit/Price Sub-Total"); WriteLine("-----------------------------------------"); WriteLine("Shirts{0,9} {1:C} {2:C}", numberOfShirts, PriceOneShirt, subTotalShirts); WriteLine("Pants{0,10} {1:C} {2:C}", numberOfPants, PriceAPairOfPants, subTotalPants); WriteLine("Other Items{0,4} {1:C} {2:C}", numberOfOtherItems, PriceOtherItem, subTotalOtherItems); WriteLine("-----------------------------------------"); WriteLine("Total Order: {0:C,20}", totalOrder.ToString()); WriteLine("Tax Rate: {0:P}", TaxRate / 100); WriteLine("Tax Amount: {0:C}", taxAmount); WriteLine("Net Price: {0:C}", salesTotal); WriteLine("-----------------------------------------"); WriteLine("Amount Tended: {0:C}", amountTended); WriteLine("Difference: {0:C}", moneyChange); WriteLine("========================================="); return 0; } }
=============================================== -/- Georgetown Dry Cleaning Services -/- ============================================== Enter Customer Name: Ricardo Sanchez Enter Customer Phone: (443) 142-3048 Enter the order date (mm/dd/yyyy): 06/22/2019 Enter the order time (hh:mm AM/PM): 11:27 AM Number of Shirts: five The value you typed for the number of shirts is not a valid number. Number of Pants: 3 Number of Other Items: Seven The value you typed for the number of other types of items is not a valid number . ----------------------------------------- The Total order is: $6.82 Amount Tended? Ten
========================================= -/- Georgetown Dry Cleaning Services -/- ========================================= Customer: Ricardo Sanchez Home Phone: (443) 142-3048 Order Date: 06/22/2019 Order Time: 11:27 AM ----------------------------------------- Item Type Qty Unit/Price Sub-Total ----------------------------------------- Shirts 0 $1.25 $0.00 Pants 3 $2.15 $6.45 Other Items 0 $3.45 $0.00 ----------------------------------------- Total Order: $6.45 Tax Rate: 5.75 % Tax Amount: $0.37 Net Price: $6.82 ----------------------------------------- Amount Tended: $0.00 Difference: ($6.82) ========================================= Press any key to continue . . .
Exceptions in the .NET Framework
The Exception Class
When dealing with errors if your application, you can deal with any exception of your choice. To customize exception handling, you may need to use some classes, such as your own class(es). Before considering that, 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.
Normally, Exception mostly serves as the general class of exceptions. 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.
The Exception's Message
In exception handling, errors are dealt with in the catch section. To do this, use catch as if it were a method. This means that, on the right side of catch, open a parenthesis, declare a variable of the type of exception you want to deal with. By default, an exception is first of type Exception. Based on this, a typical formula to implement exception handling is:
try { // Process the normal flow of the program here } catch(Exception e) { // Deal with the exception here }
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 access this Exception.Message property to display an error message if you want. Here is an example:
using System; public class Geometry { static int Main() { double side; Console.WriteLine("Square Processing"); try { Console.Write("Enter Side: "); side = double.Parse(Console.ReadLine()); Console.WriteLine("Square Characteristics"); Console.WriteLine("Side: {0}", side); Console.WriteLine("Perimeter: {0}", side * 4); } catch(Exception ex) { Console.WriteLine(ex.Message); } return 0; } }
Here is an example of running the program:
Square Processing Enter Side: Wer24 Input string was not in a correct format. Press any key to continue . . .
Custom Error Messages
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:
using System;
public class Geometry
{
static int Main()
{
double side;
Console.WriteLine("Square Processing");
try
{
Console.Write("Enter Side: ");
side = double.Parse(Console.ReadLine());
Console.WriteLine("Square Characteristics");
Console.WriteLine("Side: {0}", side);
Console.WriteLine("Perimeter: {0}", side * 4);
}
catch(Exception ex)
{
Console.WriteLine("The operation could not be carried because " +
"the number you typed is not valid");
}
return 0;
}
}
Here is an example of running the program:
Square Processing Enter Side: 24.Gh The operation could not be carried because the number you typed is not valid Press any key to continue . . .
You can also combine the Exception.Message message and your own message:
using System;
public class Geometry
{
static int Main()
{
double side;
Console.WriteLine("Square Processing");
try
{
Console.Write("Enter Side: ");
side = double.Parse(Console.ReadLine());
Console.WriteLine("Square Characteristics");
Console.WriteLine("Side: {0}", side);
Console.WriteLine("Perimeter: {0}", side * 4);
}
catch(Exception ex)
{
Console.Write(ex.Message);
Console.WriteLine("Consequently, The operation could not be carried because " +
"the number you typed is not valid");
}
return 0;
}
}
Here is an example of running the program:
Square Processing Enter Side: 25.KL48 Input string was not in a correct format.. Consequently, The operation could not be carried because the number you typed is not valid Press any key to continue . . .
A Review of .NET Exception Classes
Introduction
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 regularly use in our application.
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 name to the catch() clause. You don't have to name the argument. Then, in the catch() section, display a custom message. The second option you have consists of using the throw keyword. We will study it later.
From now on, we will try to always indicate the type of exception that could be thrown if something goes wrong in a program
The FormatException Exception
When studying data formatting, we saw that everything the user types into an application using the keyboard is primarily a string and that 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 an error. The error is of the FormatException class.
Here is a program that deals with a FormatException exception:
using System;
public class Geometry
{
static int Main()
{
double side;
Console.WriteLine("Square Processing");
try
{
Console.Write("Enter Side: ");
side = double.Parse(Console.ReadLine());
Console.WriteLine("Square Characteristics");
Console.WriteLine("Side: {0}", side);
Console.WriteLine("Perimeter: {0}", side * 4);
}
catch(FormatException)
{
Console.WriteLine("You typed an invalid number");
}
return 0;
}
}
Here is an example of running the program:
Square Processing Enter Side: 25.9G You typed an invalid number Press any key to continue . . .
Practical Learning: Using the FormatException Class
using static System.Console; public class OrderProcessing { public static int Main() { // Price of items const double PriceOneShirt = 1.25; const double PriceAPairOfPants = 2.15; const double PriceOtherItem = 3.45; const double TaxRate = 5.75; // 5.75% // Basic information about an order string customerName, homePhone; string orderDate, orderTime; // Unsigned numbers to represent cleaning items int numberOfShirts = 0, numberOfPants = 0, numberOfOtherItems = 0; // Each of these sub totals will be used for cleaning items double subTotalShirts, subTotalPants, subTotalOtherItems; // Values used to process an order double totalOrder, taxAmount, salesTotal; double amountTended = 0, moneyChange; Title = "Georgetown Dry Cleaning Services"; WriteLine("==============================================="); WriteLine("-/- Georgetown Dry Cleaning Services -/-"); WriteLine("=============================================="); // Request order information from the user Write("Enter Customer Name: "); customerName = ReadLine(); Write("Enter Customer Phone: "); homePhone = ReadLine(); Write("Enter the order date (mm/dd/yyyy): "); orderDate = ReadLine(); Write("Enter the order time (hh:mm AM/PM): "); orderTime = ReadLine(); // Request the quantity of each category of items Write("Number of Shirts: "); string strShirts = ReadLine(); numberOfShirts = int.Parse(strShirts); Write("Number of Pants: "); string strPants = ReadLine(); numberOfPants = int.Parse(strPants); Write("Number of Other Items: "); string strDresses = ReadLine(); numberOfOtherItems = int.Parse(strDresses); // Perform the necessary calculations subTotalShirts = numberOfShirts * PriceOneShirt; subTotalPants = numberOfPants * PriceAPairOfPants; subTotalOtherItems = numberOfOtherItems * PriceOtherItem; // Calculate the "temporary" total of the order totalOrder = subTotalShirts + subTotalPants + subTotalOtherItems; // Calculate the tax amount using a constant rate taxAmount = totalOrder * TaxRate / 100.00; // Add the tax amount to the total order salesTotal = totalOrder + taxAmount; WriteLine("-----------------------------------------"); // Communicate the total to the user... WriteLine("The Total order is: {0:C}", salesTotal); // and request money for the order Write("Amount Tended? "); amountTended = double.Parse(ReadLine()); // Calculate the difference owed to the customer // or that the customer still owes to the store moneyChange = amountTended - salesTotal; Clear(); Title = "Georgetown Dry Cleaning Services"; // Display the receipt WriteLine("========================================="); WriteLine("-/- Georgetown Dry Cleaning Services -/-"); WriteLine("========================================="); WriteLine("Customer: {0}", customerName); WriteLine("Home Phone: {0}", homePhone); WriteLine("Order Date: {0}", orderDate); WriteLine("Order Time: {0}", orderTime); WriteLine("-----------------------------------------"); WriteLine("Item Type Qty Unit/Price Sub-Total"); WriteLine("-----------------------------------------"); WriteLine("Shirts{0,9} {1:C} {2:C}", numberOfShirts, PriceOneShirt, subTotalShirts); WriteLine("Pants{0,10} {1:C} {2:C}", numberOfPants, PriceAPairOfPants, subTotalPants); WriteLine("Other Items{0,4} {1:C} {2:C}", numberOfOtherItems, PriceOtherItem, subTotalOtherItems); WriteLine("-----------------------------------------"); WriteLine("Total Order: {0:C}", totalOrder); WriteLine("Tax Rate: {0:P}", TaxRate / 100); WriteLine("Tax Amount: {0:C}", taxAmount); WriteLine("Net Price: {0:C}", salesTotal); WriteLine("-----------------------------------------"); WriteLine("Amount Tended: {0:C}", amountTended); WriteLine("Difference: {0:C}", moneyChange); WriteLine("========================================="); return 0; } }
=============================================== -/- Georgetown Dry Cleaning Services -/- ============================================== Enter Customer Name: Ricardo Sanchez Enter Customer Phone: (443) 142-3048 Enter the order date (mm/dd/yyyy): 06/22/2019 Enter the order time (hh:mm AM/PM): 11:27 AM Number of Shirts: five
using static System.Console; public class OrderProcessing { public static int Main() { // Price of items const double PriceOneShirt = 1.25; const double PriceAPairOfPants = 2.15; const double PriceOtherItem = 3.45; const double TaxRate = 5.75; // 5.75% // Basic information about an order string customerName, homePhone; string orderDate, orderTime; // Unsigned numbers to represent cleaning items int numberOfShirts = 0, numberOfPants = 0, numberOfOtherItems = 0; // Each of these sub totals will be used for cleaning items double subTotalShirts, subTotalPants, subTotalOtherItems; // Values used to process an order double totalOrder, taxAmount, salesTotal; double amountTended = 0, moneyChange; Title = "Georgetown Dry Cleaning Services"; WriteLine("==============================================="); WriteLine("-/- Georgetown Dry Cleaning Services -/-"); WriteLine("=============================================="); // Request order information from the user Write("Enter Customer Name: "); customerName = ReadLine(); Write("Enter Customer Phone: "); homePhone = ReadLine(); Write("Enter the order date (mm/dd/yyyy): "); orderDate = ReadLine(); Write("Enter the order time (hh:mm AM/PM): "); orderTime = ReadLine(); // Request the quantity of each category of items try { Write("Number of Shirts: "); string strShirts = ReadLine(); numberOfShirts = int.Parse(strShirts); } catch { WriteLine("The value you typed for the number of " + "shirts is not a valid number."); } try { Write("Number of Pants: "); string strPants = ReadLine(); numberOfPants = int.Parse(strPants); } catch { WriteLine("The value you typed for the number of " + "pants is not a valid number."); } try { Write("Number of Other Items: "); string strDresses = ReadLine(); numberOfOtherItems = int.Parse(strDresses); } catch { WriteLine("The value you typed for the number of " + "other types of items is not a valid number."); } // Perform the necessary calculations subTotalShirts = numberOfShirts * PriceOneShirt; subTotalPants = numberOfPants * PriceAPairOfPants; subTotalOtherItems = numberOfOtherItems * PriceOtherItem; // Calculate the "temporary" total of the order totalOrder = subTotalShirts + subTotalPants + subTotalOtherItems; // Calculate the tax amount using a constant rate taxAmount = totalOrder * TaxRate / 100.00; // Add the tax amount to the total order salesTotal = totalOrder + taxAmount; WriteLine("-----------------------------------------"); // Communicate the total to the user... WriteLine("The Total order is: {0:C}", salesTotal); // and request money for the order try { Write("Amount Tended? "); amountTended = double.Parse(ReadLine()); } catch { WriteLine("You were asked to enter an amount of money but something bad happened."); } // Calculate the difference owed to the customer // or that the customer still owes to the store moneyChange = amountTended - salesTotal; Clear(); Title = "Georgetown Dry Cleaning Services"; // Display the receipt WriteLine("========================================="); WriteLine("-/- Georgetown Dry Cleaning Services -/-"); WriteLine("========================================="); WriteLine("Customer: {0}", customerName); WriteLine("Home Phone: {0}", homePhone); WriteLine("Order Date: {0}", orderDate); WriteLine("Order Time: {0}", orderTime); WriteLine("-----------------------------------------"); WriteLine("Item Type Qty Unit/Price Sub-Total"); WriteLine("-----------------------------------------"); WriteLine("Shirts{0,9} {1:C} {2:C}", numberOfShirts, PriceOneShirt, subTotalShirts); WriteLine("Pants{0,10} {1:C} {2:C}", numberOfPants, PriceAPairOfPants, subTotalPants); WriteLine("Other Items{0,4} {1:C} {2:C}", numberOfOtherItems, PriceOtherItem, subTotalOtherItems); WriteLine("-----------------------------------------"); WriteLine("Total Order: {0:C}", totalOrder); WriteLine("Tax Rate: {0:P}", TaxRate / 100); WriteLine("Tax Amount: {0:C}", taxAmount); WriteLine("Net Price: {0:C}", salesTotal); WriteLine("-----------------------------------------"); WriteLine("Amount Tended: {0:C}", amountTended); WriteLine("Difference: {0:C}", moneyChange); WriteLine("========================================="); return 0; } }
=============================================== -/- Georgetown Dry Cleaning Services -/- ============================================== Enter Customer Name: Ricardo Sanchez Enter Customer Phone: (443) 142-3048 Enter the order date (mm/dd/yyyy): 06/22/2019 Enter the order time (hh:mm AM/PM): 11:27 AM Number of Shirts: five The value you typed for the number of shirts is not a valid number. Number of Pants: 3 Number of Other Items: Seven The value you typed for the number of other types of items is not a valid number . ----------------------------------------- The Total order is: $6.82 Amount Tended? Ten
========================================= -/- Georgetown Dry Cleaning Services -/- ========================================= Customer: Ricardo Sanchez Home Phone: (443) 142-3048 Order Date: 06/22/2019 Order Time: 11:27 AM ----------------------------------------- Item Type Qty Unit/Price Sub-Total ----------------------------------------- Shirts 0 $1.25 $0.00 Pants 3 $2.15 $6.45 Other Items 0 $3.45 $0.00 ----------------------------------------- Total Order: $6.45 Tax Rate: 5.75 % Tax Amount: $0.37 Net Price: $6.82 ----------------------------------------- Amount Tended: $0.00 Difference: ($6.82) ========================================= Press any key to continue . . .
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, as we saw when studying variables and data types in Lesson 1 and 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:
using System; // An Exercise class class Exercise { static int Main() { byte NumberOfPages; Console.Write("Enter the number of pages of the newspaper: "); NumberOfPages = byte.Parse(Console.ReadLine()); Console.WriteLine("Number of Pages of the Newspaper: {0}", NumberOfPages); } return 0; }
When a value beyond the allowable range is asked to be stored in memory, the compiler produces (the expression is "throws" as we will learn soon) an error of the OverflowException class. Here is an example of running the program:
Enter the number of pages of the newspaper: 824 Unhandled Exception: System.OverflowException: Value was either too large or too small for an unsigned byte. at System.Byte.Parse(String s, NumberStyles style, IFormatProvider provider) at System.Byte.Parse(String s) at Exercise.Main() in c:\programs\msvcs .net 2003\project17\exercise.cs:line 11
As with the other errors, when this exception is thrown, you should take an appropriate action.
The ArgumentOutOfRangeException Exception
Once again, when studying the techniques of converting or formatting values in Lesson 5, we saw that a value was 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 value, 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 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:
using System; // An Exercise class class Exercise { static int Main() { DateTime DateHired; Console.Write("Enter Date Hired: "); DateHired = DateTime.Parse(Console.ReadLine()); Console.WriteLine("Date Hired: {0:d}", DateHired); return 0; } }
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:
Enter Date Hired: 1244/04/258 Unhandled Exception: System.FormatException: String was not recognized as a valid DateTime. at System.DateTimeParse.Lex(Int32 dps, __DTString str, DateTimeToken dtok, DateTimeRawInfo raw, DateTimeResult result, DateTimeFormatInfo& dtfi) at System.DateTimeParse.Parse(String s, DateTimeFormatInfo dtfi, DateTimeStyles styles) at System.DateTime.Parse(String s, IFormatProvider provider, DateTimeStyles styles) at System.DateTime.Parse(String s, IFormatProvider provider) at System.DateTime.Parse(String s) at Exercise.Main() in c:\programs\msvcs .net 2003\project17\exercise.cs:line 11
One way you can avoid this is to guide the user but still take appropriate actions.
The DivideByZeroException 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 is performed, the compiler produces a DivideByZeroException exception.
Practical Learning: Ending the Lesson
|
||
Previous | Copyright © 2008-2019, FunctionX | Next |
|