Introduction to Exceptions

Overview

So far (in previous lessons), we have learned to perform various types of operations that involve numeric values. What we did so far was to avoid bad occurrences. The reality is that bad occurrences are a reality of life. We need to learn how to deal with them so we can assist the users of our application when an error occurs in our application.

Practical Learning: Introducing Exception Handling

1. Start Microsoft Visual Studio. Create a new Console App named PledgeDistribution1 that uses the .NET 8.0 (Long-Term Support)
2. In the Solution Explorer, right-click Program.cs and click Rename
3. Type FundRaising (to get FundRaising.cs) and press Enter twice
4. Change the document as follows:
```using static System.Console;

int DistributeFirstPart(int amount, int portion1, int portion2)
{
int totalRatios = portion1 + portion2;
int eachPart = amount / totalRatios;
int result = eachPart * portion1;

return result;
}

int Subtract(int first, int second)
{
return first - second;
}

int amtPledged;
int ratio1;
int ratio2;
int part1;
int part2;

WriteLine("===================================================");
WriteLine("Pledge Distribution");
WriteLine("===================================================");
WriteLine("Type the values to evaluate a pledge distribution");
Write("Amount to Allocate:  ");
Write("Portion 1:           ");
Write("Portion 2:           ");

part1 = DistributeFirstPart(amtPledged, ratio1, ratio2);
part2 = Subtract(amtPledged, part1);

WriteLine("===================================================");
WriteLine("Pledge Distribution");
WriteLine("===================================================");
WriteLine(\$"Amouont Allocated:   {amtPledged}");
WriteLine(\$"Portion 1:           {ratio1}");
WriteLine(\$"Portion 2:           {ratio2}");
WriteLine("---------------------------------------------------");
WriteLine(\$"Part 1:              {part1}");
WriteLine(\$"Part 2:              {part2}");
WriteLine("===================================================");```
6. When requested, type the Amount to Allocate 6450 and press Enter
7. Type Portion 1 as 1 and press Enter
8. Type Portion 2 as 1 and press Enter:
```===================================================
Pledge Distribution
===================================================
Type the values to evaluate a pledge distribution
Amount to Allocate:  6450
Portion 1:           1
Portion 2:           1
===================================================
Pledge Distribution
===================================================
Amouont Allocated:   6450
Portion 1:           1
Portion 2:           1
---------------------------------------------------
Part 1:              3225
Part 2:              3225
===================================================

Press any key to close this window . . .```

Exceptional Behaviors

An exception is an unusual situation that could occur in your project. 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. C# provides many keywords to deal with an exception:

1. Trying the normal flow: To deal with the expected behavior of a program, use the try keyword as in the following formula:
`try {behavior}`
The try keyword is required. It lets the compiler know that you are attempting a normal flow of your program. The actual behavior that needs to be evaluated is included between an opening curly bracket "{" and a closing curly bracket "}". Inside the brackets, implement the normal flow that the program must follow, at least for this section of the code. Here is an example:
```double number, result;

try
{
result = number * 2.00;
}```
2. Catching Errors: During the flow of the program as part of the try section, if an abnormal behavior occurs, instead of letting the webpage display an error, you can transfer the flow of the code to another section that can deal with it. The syntax used by this section is:
`catch {what-to-do}`
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 syntax of an exception would be:
```try
{
// Try the program flow
}
catch
{
// Catch the exception
}```

Practical Learning: Introducing Exceptional Behaviors

1. To introduce exceptions, change the code as follows:
```using static System.Console;

int DistributeFirstPart(int amount, int portion1, int portion2)
{
int totalRatios = portion1 + portion2;
int eachPart = amount / totalRatios;
int result = eachPart * portion1;

return result;
}

int Subtract(int first, int second)
{
return first - second;
}

try
{
int amtPledged;
int ratio1;
int ratio2;
int part1;
int part2;

WriteLine("===================================================");
WriteLine("Pledge Distribution");
WriteLine("===================================================");
WriteLine("Type the values to evaluate a pledge distribution");
Write("Amount to Allocate:  ");
Write("Portion 1:           ");
Write("Portion 2:           ");

part1 = DistributeFirstPart(amtPledged, ratio1, ratio2);
part2 = Subtract(amtPledged, part1);

WriteLine("===================================================");
WriteLine("Pledge Distribution");
WriteLine("===================================================");
WriteLine(\$"Amouont Allocated:   {amtPledged}");
WriteLine(\$"Portion 1:           {ratio1}");
WriteLine(\$"Portion 2:           {ratio2}");
WriteLine("---------------------------------------------------");
WriteLine(\$"Part 1:              {part1}");
WriteLine(\$"Part 2:              {part2}");
WriteLine("===================================================");
}
catch
{

}```
3. Type the Amount Allocated as 1250000
4. Press Enter twice
```===================================================
Pledge Distribution
===================================================
Type the values to evaluate a pledge distribution
Amount to Allocate:  125000
Portion 1:

Press any key to close this window . . .```

Exceptions and Custom Messages

As mentioned already, if an error occurs when processing the code 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:

```double number, result;

try
{
result = number * 2.00;
}
catch
{
WriteLine("The value you entered is not a valid number.")
}```

Practical Learning: Displaying Custom Messages

1. To display custom messages to the visitor, change the code as follows:
```using static System.Console;

int DistributeFirstPart(int amount, int portion1, int portion2)
{
int totalRatios = portion1 + portion2;
int eachPart = amount / totalRatios;
int result = eachPart * portion1;

return result;
}

int Subtract(int first, int second)
{
return first - second;
}

try
{
int amtPledged;
int ratio1;
int ratio2;
int part1;
int part2;

WriteLine("===================================================");
WriteLine("Pledge Distribution");
WriteLine("===================================================");
WriteLine("Type the values to evaluate a pledge distribution");
Write("Amount to Allocate:  ");
Write("Portion 1:           ");
Write("Portion 2:           ");
part1 = DistributeFirstPart(amtPledged, ratio1, ratio2);
part2 = Subtract(amtPledged, part1);

WriteLine("===================================================");
WriteLine("Pledge Distribution");
WriteLine("===================================================");
WriteLine(\$"Amouont Allocated:   {amtPledged}");
WriteLine(\$"Portion 1:           {ratio1}");
WriteLine(\$"Portion 2:           {ratio2}");
WriteLine("---------------------------------------------------");
WriteLine(\$"Part 1:              {part1}");
WriteLine(\$"Part 2:              {part2}");
WriteLine("===================================================");
}
catch
{
WriteLine("The value you entered for the amount to pledge " +
"or the amount to allocate is not valid. ");
WriteLine("Please type a valid value (such as 200, 1250, 5000, or 100000).");
}```
3. When requested, type the Amount to Allocate as Nothing and press Enter
```===================================================
Pledge Distribution
===================================================
Type the values to evaluate a pledge distribution
Amount to Allocate:  Nothing
The value you entered for the amount to pledge or the amount to allocate is not valid.
Please type a valid value (such as 200, 1250, 5000, or 100000).

Press any key to close this window . . .```

Introduction to .NET Exceptions

The Exception Class

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.

In exception handling, errors are dealt with in the catch section. Therefore, use catch as if it were a method. This means that, on the right side of catch, add some parentheses. In the parentheses, pass a parameter 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
}```

The Message of an Exception

When an exception occurs in the try section, code compilation is transferred to the catch section. If you pass 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 is of type string. It describes the type of error that occurred. You can then use this Exception.Message property to display an error message if you want.

Practical Learning: Introducing the Exception Class

1. Change the code as follows:
```using static System.Console;

int DistributeFirstPart(int amount, int portion1, int portion2)
{
int totalRatios = portion1 + portion2;
int eachPart = amount / totalRatios;
int result = eachPart * portion1;

return result;
}

int Subtract(int first, int second)
{
return first - second;
}

try
{
int amtPledged;
int ratio1;
int ratio2;
int part1;
int part2;

WriteLine("===================================================");
WriteLine("Pledge Distribution");
WriteLine("===================================================");
WriteLine("Type the values to evaluate a pledge distribution");
Write("Amount to Allocate:  ");
Write("Portion 1:           ");
Write("Portion 2:           ");

part1 = DistributeFirstPart(amtPledged, ratio1, ratio2);
part2 = Subtract(amtPledged, part1);

WriteLine("===================================================");
WriteLine("Pledge Distribution");
WriteLine("===================================================");
WriteLine(\$"Amouont Allocated:   {amtPledged}");
WriteLine(\$"Portion 1:           {ratio1}");
WriteLine(\$"Portion 2:           {ratio2}");
WriteLine("---------------------------------------------------");
WriteLine(\$"Part 1:              {part1}");
WriteLine(\$"Part 2:              {part2}");
WriteLine("===================================================");
}
catch(Exception exc)
{
WriteLine(exc.Message);
}```
3. When requested, type the Amount to Allocated as I am giving and press Enter
```===================================================
Pledge Distribution
===================================================
Type the values to evaluate a pledge distribution
Amount to Allocate:  I am giving
The input string 'I am giving' was not in a correct format.

Press any key to close this window . . .```

Introduction to Custom Error Messages

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 visitor because, in some cases, the user may not understand what the expression "correct format" means and why it is being used. As an alternative, you can create your own message and display it to the user. One way to do this is to create a message box in a catch clause. Here is an example:

```double number, result;

try {
result = number * 2.00;
}
catch(Exception exc)
{
WriteLine("The operation could not be carried because " +
"the number you typed is not valid";
}```

If you use the above technique, in some cases, the C# compiler, or some C# compilers, may present a warning because you didn't use the argument. To address this issue, you have various options. You can pass the parameter as an underscore and not use that underscore in the catch section (but you may receive the same warning as previously). Here is an example:

```void Calculate()
{
try
{
}
catch(Exception _)
{
WriteLine(" The value you entered for the amount to allocate " +
"or pledge is not valid. Only natural numbers " +
"(such as 200, 1250, 5000, or 100000) are allowed.");
}
}```

You can use only the message of the argument as seen earlier:

```void Calculate()
{
try
{
}
catch(Exception exc)
{
WriteLine(exc.Message);
}
}```

You can combine the Exception.Message message and your own message. Here is an example:

```void Calculate()
{
try
{
}
catch(Exception exc)
{
WriteLine(exc.Message +
" The value you entered for the amount to allocate " +
"or pledge is not valid. Only natural numbers " +
"(such as 200, 1250, 5000, or 100000) are allowed.");
}
}```

The last, sometimes the best, solution is to not name the parameter. Here is an example:

```void Calculate()
{
try
{
}
catch(Exception)
{
WriteLine(" The value you entered for the amount to allocate " +
"or pledge is not valid. Only natural numbers " +
"(such as 200, 1250, 5000, or 100000) are allowed.");
}
}```

In some cases, you will want to create a custom error message but send it to another section of the project. To assist you with this, the Exception class with equipped with a constructor that takes a string as argument.

A Custom Exception Class

You can create your own class to deal with exceptions in your project, and you can create such a class from scratch. Instead of going through such a complicated adventure, a better alternative is derive a class from Exception. Here is an example:

```public class UnwantedBehavior : Exception
{
}```

By tradition, a class that derives from Exception must have a name that ends with Exception. Here is an example:

```public class UnwantedBehaviorException : Exception
{
}```

To assist you with exceptions, the .NET Framework provides a rich collection of classes for exceptions. Therefore, before creating your own exception class, first find out if there is already an exception class that provides the behavior you want, and use that built-in class.

Introduction to Built-In Exception Classes

Overview

The .NET Framework provides various classes to handle almost any type of exception. When your application produces an error, the compiler will display a message to notify the user.

To identify the primary class that deals with the exception, click the Details button.

There are two main ways you can use one of the classes of the .NET Framework. If you know that a particular exception will be produced, pass its name to a catch() clause. You don't have to name the argument. Then, in the catch section, display a custom message.

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 compiler produces an error. The error is of a class named FormatException.

Here is a program that deals with a FormatException exception:

```double number, result;

try {
WriteLine("Number:");
number = double.Parse(Request[]);
result = number * 2.00;
}
catch(FormatException exc)
{
WriteLine("The value you entered is not a valid number.");
}```

Practical Learning: Using the FormatException Class

1. Change the code as follows:
```using static System.Console;

int DistributeFirstPart(int amount, int portion1, int portion2)
{
int totalRatios = portion1 + portion2;
int eachPart = amount / totalRatios;
int result = eachPart * portion1;

return result;
}

int Subtract(int first, int second)
{
return first - second;
}

try
{
int amtPledged;
int ratio1;
int ratio2;
int part1;
int part2;

WriteLine("===================================================");
WriteLine("Pledge Distribution");
WriteLine("===================================================");
WriteLine("Type the values to evaluate a pledge distribution");
Write("Amount to Allocate:  ");
Write("Portion 1:           ");
Write("Portion 2:           ");

part1 = DistributeFirstPart(amtPledged, ratio1, ratio2);
part2 = Subtract(amtPledged, part1);

WriteLine("===================================================");
WriteLine("Pledge Distribution");
WriteLine("===================================================");
WriteLine(\$"Amouont Allocated:   {amtPledged}");
WriteLine(\$"Portion 1:           {ratio1}");
WriteLine(\$"Portion 2:           {ratio2}");
WriteLine("---------------------------------------------------");
WriteLine(\$"Part 1:              {part1}");
WriteLine(\$"Part 2:              {part2}");
WriteLine("===================================================");
}
catch (FormatException)
{
WriteLine("The value you entered for the amount to pledge " +
"(or to allocate) is not valid. ");
WriteLine("Please type a valid value (such as 200, 1250, 5000, or 100000).");
}```
3. For the Amount to Allocate, type 6250 and press Enter
4. For Portion 1, type 3 and press Enter
5. For Portion 2, type 2 and press Enter
```===================================================
Pledge Distribution
===================================================
Type the values to evaluate a pledge distribution
Amount to Allocate:  6250
Portion 1:           3
Portion 2:           2
===================================================
Pledge Distribution
===================================================
Amouont Allocated:   6250
Portion 1:           3
Portion 2:           2
---------------------------------------------------
Part 1:              3750
Part 2:              2500
===================================================

Press any key to close this window . . .```
7. Change the document as follows:
```using static System.Console;

(int, int) DistributeParts(int amount, int portion1, int portion2)
{
int totalRatios = portion1 + portion2;
int eachPart    = amount / totalRatios;
int result      = eachPart * portion1;

return (result, amount - result);
}

int Subtract(int first, int second)
{
return first - second;
}

try
{
int amtPledged;
int ratio1;
int ratio2;

WriteLine("===================================================");
WriteLine("Pledge Distribution");
WriteLine("===================================================");
WriteLine("Type the values to evaluate a pledge distribution");
Write("Amount to Allocate:  ");
Write("Portion 1:           ");
Write("Portion 2:           ");

(int first, int second) portions = DistributeParts(amtPledged, ratio1, ratio2);

WriteLine("===================================================");
WriteLine("Pledge Distribution");
WriteLine("===================================================");
WriteLine(\$"Amouont Allocated:   {amtPledged}");
WriteLine(\$"Portion 1:           {ratio1}");
WriteLine(\$"Portion 2:           {ratio2}");
WriteLine("---------------------------------------------------");
WriteLine(\$"Part 1:              {portions.first}");
WriteLine(\$"Part 2:              {portions.second}");
WriteLine("===================================================");
}
catch (FormatException fe)
{
WriteLine("The value you entered for the amount to pledge " +
"(or to allocate) is not valid. ");
WriteLine("Please type a valid value (such as 200, 1250, 5000, or 100000).");

WriteLine("The error produced is: " + fe.Message);
}
}```
9. For the Amount to Allocate, type 8500 and press Enter
10. For Portion 1, type 4 and press Enter
11. For Portion 2, type 3 and press Enter
```===================================================
Pledge Distribution
===================================================
Type the values to evaluate a pledge distribution
Amount to Allocate:  8500
Portion 1:           4
Portion 2:           3
===================================================
Pledge Distribution
===================================================
Amouont Allocated:   8500
Portion 1:           4
Portion 2:           3
---------------------------------------------------
Part 1:              4856
Part 2:              3644
===================================================

Press any key to close this window . . .```

The Overflow Exception

An application receives, processes, and produces values on a regular basis. To better manage these values, as we saw when studying variables and data types in previous lessons, the compiler uses appropriate amounts of space to store its values. If you provide a value higher than the data type allows, you will get an error.

When a value beyond the allowable range is asked to be stored in memory, the compiler produces an error of a class named OverflowException.

The Argument Out of Range Exception

If the user provides a value that is outside a range allowed by its type or class and therefore cannot be converted appropriately, the compiler produces an exception of a class named ArgumentOutOfRangeException.

The Divide by Zero Exception

If your application tries to divide a number by 0, the compiler produces an error of a class named DivideByZeroException.

Practical Learning: Handling Exceptions