Introduction to Exception Handling in C#
Introduction to Exception Handling in C#
Introduction to Exceptions
Overview
Imagine you want to write a webpage 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:
@{ ViewBag.Title = "Calculations"; } <h2>Calculations</h2> @{ double number = 0.00; double result = 0.00; if (IsPost) { number = double.Parse(Request["txtNumber"]); result = number * 2.00; } } @using (Html.BeginForm()) { <table> <tr> <td>Number:</td> <td>@Html.TextBox("txtNumber", @number)</td> </tr> <tr> <td> </td> <td><input type="submit" name="btnCalculate" value="Calculate" /></td> </tr> <tr> <td>Result:</td> <td>@Html.TextBox("txtResult", @result)</td> </tr> </table> }
This looks like an easy request. When it comes up, the user is asked to simply type a number. Here is an example:
When the user clicks the button, the number that was entered is then multiplied by 2 and display the result. Here is an example:
Imagine that a user leaves the text box empty or types something that is not a valid number, such as the name of a country, somebody's telephone number, or just anything. Here is an example:
Since the form 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 perform the assignment, for any reason it is not prepared for, it would produce an error.
Practical Learning: Introducing Exception Handling
@media screen and (min-width: 768px) { .jumbotron { padding-top: 48px; padding-bottom: 48px; } .container .jumbotron { padding-right: 60px; padding-left: 60px; } .jumbotron h1 { font-size: 63px; } }
body { padding-top: 50px; padding-bottom: 20px; } .glued-part { top: 0; width: 100%; height: 75px; position: fixed; background-color: white; } .heading-format { font-weight: 800; font-family: Cambria, Cochin, Georgia, Times, Times New Roman, serif; } .heading1 { color: maroon; font-size: 2.52em; line-height: 2.05em; } .heading2 { color: #b71f1f; margin-top: 20px; font-size: 1.52em; line-height: 1.15em; } .navbar-fixed-top { top: 75px; } .navbar-inverse { background-color: #581405; border-top: 3px solid black; border-bottom: 3px solid black; } .jumbotron { padding-top: 80px; background-color: white; border: 1px solid burlywood } .contents { width: 300px; margin: auto; margin-top: 40px; } .content2Parts { width: 300px; } .content3Parts { width: 350px; } .left-column { width: 140px; } .tbx-format { width: 50px; } .lead { margin-bottom: 0; } .pic-holder { text-align: center; } .left-column { width: 140px; } .tbx-format { width: 40px; }
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>OFRE :: @ViewBag.Title</title> @Styles.Render("~/Content/css") @Scripts.Render("~/bundles/modernizr") <link rel="stylesheet" type="text/css" href="~/Content/FundRaising.css" /> </head> <body> <div class="glued-part"> <p class="heading1 heading-format text-center">Organization for Fundraising Events</p> </div> <div class="navbar navbar-inverse navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> </div> <div class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li>@Html.ActionLink("Home", "Index", "Home")</li> <li>@Html.ActionLink("About OFRE", "About", "Home")</li> <li>@Html.ActionLink("Contact Us", "Contact", "Home")</li> </ul> </div> </div> </div> <div class="container body-content"> @RenderBody() <hr /> <footer> <h4 class="text-center">© @DateTime.Now.Year :: Organization for Fundraising Events</h4> </footer> </div> @Scripts.Render("~/bundles/jquery") @Scripts.Render("~/bundles/bootstrap") @RenderSection("scripts", required: false) </body> </html>
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace OFRE4.Controllers { public class CampaignsController : Controller { // GET: Campaigns public ActionResult Index() { return View(); } // GET: TwoWay public ActionResult TwoWay() { return View(); } // GET: ThreeWay public ActionResult ThreeWay() { return View(); } public int DistributeFirstPart(int amount, int portion1, int portion2) { int totalRatios = portion1 + portion2; int eachPart = amount / totalRatios; int result = eachPart * portion1; return result; } public int Subtract(int first, int second) { return first - second; } } }
@{ ViewBag.Title = "OFRE Home"; } <div class="jumbotron"> <h1>OFRE</h1> <p class="lead"> The Organization for Fundraising Events, or OFRE, is a group of people who assist organizations, communities, associations, schools, causes, religious institutions, etc, to plan, conduct, promote, and run campaigns to raise money for any goal (cause, health issues, communities, school, politics, ceremony, religion, catastrophe, business startup, etc). The Organization can provide a complete service, including promoting the event, collecting, and delivering the funds. OFRE is a private, independent, and a not-for-profit organization. </p> </div> <div class="row"> <div class="col-md-4"> <p class="pic-holder"><img src="~/Images/Campaign.png" alt="Plan With Us" width="248" height="137" /></p> <h2>Plan With Us</h2> <p>Are you ready for a memorable experience in fundraising? You reaached the right place. Do you lack experience in fundraising? Don't take a chance. Don't worry about a thing. Let us run your next campaign. Give us the opportunity to put our vast experience at your disposal. You will enjoy the whole adventure.</p> </div> <div class="col-md-4"> <p class="pic-holder"><img src="~/Images/TwoWay.png" alt="Two-Way Campaign" width="248" height="136" /></p> <h2>Two-Way Campaign</h2> <p>This is an already completely created program to run a campaign to raise funds for two organizations or causes. This program consists of starting a compaign, collecting funds, appropriately distributing them, and delivering a complete legal/business/financial report of the campaign.</p> @Html.ActionLink("Two-Way Campaign", "TwoWay", "Campaigns", new { DontTryToFindOutWhatThisIs = "" }, new { @class = "btn btn-default" }) </div> <div class="col-md-4"> <p class="pic-holder"><img src="~/Images/ThreeWay.png" alt="Three-Way Distribution" width="248" height="136" /></p> <h2>Three-Way Distribution</h2> <p>In this program, the Organization runs a campaign to raise funds for three different organizations or causes. The ratios of distribution are stated any way a group wants. An effective computer application is intuitively ready to process all types of requests.</p> @Html.ActionLink("Three-Way Campaign Distribution", "ThreeWay", "Campaigns", new { ThisIsJustAPlaceHolder = "" }, new { @class = "btn btn-default" }) </div> </div>
@{ ViewBag.Title = "Two-Way Campaign Distribution"; } @{ int amtPledged = 0; int ratio1 = 1; int ratio2 = 1; int portion1 = 0; int portion2 = 0; if (IsPost) { amtPledged = Convert.ToInt32(Request["txtAllocation"]); ratio1 = Convert.ToInt32(Request["txtPortion1"]); ratio2 = Convert.ToInt32(Request["txtPortion2"]); OFRE4.Controllers.CampaignsController cc = new OFRE4.Controllers.CampaignsController(); portion1 = cc.DistributeFirstPart(amtPledged, ratio1, ratio2); portion2 = cc.Subtract(amtPledged, portion1); } } <p> </p> <p> </p> <div class="contents content2Parts"> <p class="heading2 text-center heading-format">Pledge Distribution</p> <form name="frmDistribution" method="post"> <table> <tr> <td class="left-column">Amount to Allocate:</td> <td><input type="text" name="txtAllocation" value=@amtPledged /></td> </tr> </table> <table> <tr> <td class="left-column">In the Ratio:</td> <td><input type="text" name="txtPortion1" class="tbx-format" value=@ratio1 /></td> <td>:</td> <td><input type="text" class="tbx-format" name="txtPortion2" value="@ratio2" /></td> <td><input name="btnAllocate" type="submit" value="Allocate" /></td> </tr> </table> <hr /> <table> <tr> <td class="left-column">Part 1 Receives:</td> <td><input type="text" name="txtPart1" value="@portion1" /></td> </tr> <tr> <td>Part 2 Receives:</td> <td><input type="text" name="txtPart2" value="@portion2" /></td> </tr> </table> </form> </div>
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:
try {behavior}If you are writing the code in a webpage, you can precede the try keyword with the @ symbol:
@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 = 0.00; double result = 0.00; if (IsPost) { try { number = double.Parse(Request["txtNumber"]); result = number * 2.00; } } }
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 }Remember that if you are writing the code in a webpage, precede the try keyword with the @ symbol:
@try { // Try the program flow } catch { // Catch the exception }Code that includes a catch section may appear as follows:
@try
{
<p>Welcome to our website.</p>
}
catch
{
}
Practical Learning: Introducing Exceptions
@{ int amtPledged = 0; int ratio1 = 1; int ratio2 = 1; int portion1 = 0; int portion2 = 0; if (IsPost) { try { amtPledged = Convert.ToInt32(Request["txtAllocation"]); ratio1 = Convert.ToInt32(Request["txtPortion1"]); ratio2 = Convert.ToInt32(Request["txtPortion2"]); OFRE4.Controllers.CampaignsController cc = new OFRE4.Controllers.CampaignsController(); portion1 = cc.DistributeFirstPart(amtPledged, ratio1, ratio2); portion2 = cc.Subtract(amtPledged, portion1); } catch { } } }
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 = 0.00;
double result = 0.00;
string message = "";
if (IsPost)
{
try
{
number = double.Parse(Request["txtNumber"]);
result = number * 2.00;
}
catch
{
message = "The value you entered is not a valid number."
}
}
}
@using (Html.BeginForm())
{
<table>
<tr>
<td>Number:</td>
<td>@Html.TextBox("txtNumber", @number)</td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="btnCalculate" value="Calculate" /></td>
</tr>
<tr>
<td>Result:</td>
<td>@Html.TextBox("txtResult", @result)</td>
</tr>
</table>
<p>@message</p>
}
Of course, your message may not be particularly clear but this time, the webpage will not crash.
Practical Learning: Displaying Custom Messages
@{ ViewBag.Title = "Two-Way Campaign Distribution"; } @{ int amtPledged = 0; int ratio1 = 1; int ratio2 = 1; int portion1 = 0; int portion2 = 0; string strErrorMessage = ""; if (IsPost) { try { amtPledged = Convert.ToInt32(Request["txtAllocation"]); ratio1 = Convert.ToInt32(Request["txtPortion1"]); ratio2 = Convert.ToInt32(Request["txtPortion2"]); OFRE4.Controllers.CampaignsController cc = new OFRE4.Controllers.CampaignsController(); portion1 = cc.DistributeFirstPart(amtPledged, ratio1, ratio2); portion2 = cc.Subtract(amtPledged, portion1); } catch { strErrorMessage = "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."; } } } <p> </p> <p> </p> <div class="contents content2Parts"> <p class="heading2 text-center heading-format">Pledge Distribution</p> <form name="frmDistribution" method="post"> <table> <tr> <td class="left-column">Amount to Allocate:</td> <td><input type="text" name="txtAllocation" value=@amtPledged /></td> </tr> </table> <table> <tr> <td class="left-column">In the Ratio:</td> <td><input type="text" name="txtPortion1" class="tbx-format" value=@ratio1 /></td> <td>:</td> <td><input type="text" class="tbx-format" name="txtPortion2" value="@ratio2" /></td> <td><input name="btnAllocate" type="submit" value="Allocate" /></td> </tr> </table> <hr /> <table> <tr> <td class="left-column">Part 1 Receives:</td> <td><input type="text" name="txtPart1" value="@portion1" /></td> </tr> <tr> <td>Part 2 Receives:</td> <td><input type="text" name="txtPart2" value="@portion2" /></td> </tr> </table> <hr /> <table> <tr> <td>@strErrorMessage</td> </tr> </table> </form> </div>
Introduction to Exceptions in the .NET Framework
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 webpage, 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.
The Message of an Exception
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, 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 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. Here is an example:
@{ double number = 0.00; double result = 0.00; string message = ""; if (IsPost) { try { number = double.Parse(Request["txtNumber"]); result = number * 2.00; } catch(Exception exc) { message = exc.Message; } } } @using (Html.BeginForm()) { <table> <tr> <td>Number:</td> <td>@Html.TextBox("txtNumber", @number)</td> </tr> <tr> <td> </td> <td><input type="submit" name="btnCalculate" value="Calculate" /></td> </tr> <tr> <td>Result:</td> <td>@Html.TextBox("txtResult", @result)</td> </tr> </table> <p>@message</p> }
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 since, as in this case, the visitor 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. One way to do this is to formulate a message in a catch clause and assign that message to a control or a variable. Here is an example:
@{ double number = 0.00; double result = 0.00; string message = ""; if (IsPost) { try { number = double.Parse(Request["txtNumber"]); result = number * 2.00; } catch(Exception exc) { message = "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 actually use the exc argument. As one alternative, you can either use only the exc argument and access its message as seen earlier, or you can combine the Exception.Message message and your own message. Here is an example:
@{ double number = 0.00; double result = 0.00; string message = ""; if (IsPost) { try { number = double.Parse(Request["txtNumber"]); result = number * 2.00; } catch(Exception exc) { message = exc.Message + "The operation could not be carried because " + "the number you typed is not valid"; } } }
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 derive 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. 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 browser produces an error. The error is of a class named FormatException. Here is an example of a webpage that that throws this exception:
Here is a program that deals with a FormatException exception:
@{
double number = 0.00;
double result = 0.00;
string message = "";
if (IsPost)
{
try
{
number = double.Parse(Request["txtNumber"]);
result = number * 2.00;
}
catch(FormatException exc)
{
message = "The value you entered is not a valid number.";
}
}
}
Practical Learning: Using the FormatException Class
@{
int amtPledged = 0;
int ratio1 = 1;
int ratio2 = 1;
int portion1 = 0;
int portion2 = 0;
string strErrorMessage = "";
if (IsPost)
{
try
{
amtPledged = Convert.ToInt32(Request["txtAllocation"]);
ratio1 = Convert.ToInt32(Request["txtPortion1"]);
ratio2 = Convert.ToInt32(Request["txtPortion2"]);
OFRE4.Controllers.CampaignsController cc = new OFRE4.Controllers.CampaignsController();
portion1 = cc.DistributeFirstPart(amtPledged, ratio1, ratio2);
portion2 = cc.Subtract(amtPledged, portion1);
}
catch(FormatException)
{
strErrorMessage = "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 Overflow Exception
A browser 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 would 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 an attempt to divide a value by 0, the compiler produces an error of a class named DivideByZeroException.
Practical Learning: Ending the Lesson
|
||
Previous | Copyright © 2001-2019, FunctionX | Next |
|