dotnet Exception Handling

.NET Exceptions – System.Web.HttpException

Moving along through our in-depth .NET Exception Handling series, today we’ll be going over the System.Web.HttpException. The HttpException is the most basic type of web-based exception, so it can be used for many general purposes that relate to something going wrong when processing an HTTP request in an ASP.NET or similar application.

Throughout this article we’ll explore the HttpException in more detail, starting with where it sits in the overall .NET exception hierarchy. Then we’ll take a look at a fully-functional C# code sample that illustrates one example of how you might use HttpExceptions in your own code. Let’s get started!

The Technical Rundown

All .NET exceptions are derived classes of the System.Exception base class, or derived from another inherited class therein. The full exception hierarchy of this error is:

Full Code Sample

Below is the full code sample we’ll be using in this article. It can be copied and pasted if you’d like to play with the code yourself and see how everything works.

When Should You Use It?

As mentioned in the introduction, the HttpException is a baseline, generic HTTP-based exception, so it can be used in a variety of situations that you deem appropriate. In the simplest sense, an HttpException should be thrown when something goes wrong while processing any HTTP request. Thus, you can freely throw HttpExceptions throughout your web application, wherever they are appropriate.

To illustrate how you might use a HttpException in your own code our sample begins by creating a standard ASP.NET web app. There’s little reason to go through all the files included in the project, since they’re primarily all the defaults. Instead, the goal of this example code is to create a simple web form that allows the user to enter some fields to create a Book, such as Title, Author, Page Count, and Publication Date. Upon submitting the form, our code performs some basic validation on the server-side. If validation is successful, a new Book instance is created and the string format is output to the user. If validation fails, a new HttpException is thrown, indicating what went wrong so the user can resolve it.

Thus, we start with a basic Book class that includes the previously mentioned properties. It also includes a slightly modified ToString() method override, which checks if PublicationDate is present, and therefore, whether it should be included in the Book output:

Our Default.aspx page uses Bootstrap for CSS classes, but otherwise is a pretty traditional collection of TextBox fields to enter data, and associated Labels:

We’ve also added the BookSubmit_Click() method to the OnClick event of the BookSubmit Button, which will trigger our validation. The BookLabel Label will serve as a basic output for the user should anything go wrong.

Finally, the actual C# code for our Default.aspx page starts with the standard Page_Load(object sender, EventArgs e) event method, but we aren’t performing any actions in there so it’s blank:

We next have a private CreateBook() helper method that attempts to create a new Book instance using all the entered data from our Book form:

We don’t want to create a Book that has no Author or Title, so we explicitly throw a new HttpException if either field is empty. We have decided to allow PageCount to be empty, so we set the default value to 0 if it’s not empty, otherwise we convert the string value in BookPageCount.Text to an integer. Finally, we also need to check if the user has selected a date within the BookPublicationDate calendar control. If not, the value is equal to the DateTime.MinValue, so we call a different Book constructor overload then if a publication date was selected by the user.

From there, we need to add the BookSubmit_Click(object sender, EventArgs e) method, which is our event handler for when the submit button is clicked:

Here we’re just creating a new Book instance using the CreateBook() method, then outputting the newly-generated Book to the debug log, as well as formatting the BookLabel to show the user the new Book. However, if an HttpException occurs we output that to the log, and also alter the label output to display the error for the user.

With everything in place let’s run our little web application and try playing around with creating some Books. We start with all four fields (Title, Author, Page Count, and Publication Date) empty/unselected. If we click Submit without making any changes, the first validation that fails is the Title check, which outputs an HttpException to the user and the log:

Let’s enter The Stand into the Title field and try to Submit again. Now Author is the problematic field:

In our case, we’re talking about The Stand by Stephen King, so let’s add him to the Author field and Submit a third time. Lo and behold, no exceptions are thrown and we get a new Book output:

We explicitly allowed zero pages to be specified, so that’s what we get. However, that’s not quite right, so let’s change it to the correct value of 1153 and try again:

Now let’s select the publication date of September 1st, 1978 and Submit once more:

This all works as intended, but what happens if we try to use an incorrect value type? For example, let’s change the numeric Page Count field from 1153 to a written form of one-thousand, fifty-three and Submit one final time:

Here we see two exceptions are output to the log (while only the HttpException is shown to the user on the page). The reason for this is that we attempt to convert the BookPageCount.Text string value to an integer using Convert.ToInt32(...), but the string we passed cannot be parsed and converted by the default API. Therefore, this throws a System.FormatException, which we explicitly catch in the CreateBook() method, outputting that to the log and manually throwing our own HttpException that can be caught elsewhere and shown to the user.

To get the most out of your own applications and to fully manage any and all .NET Exceptions, check out the Airbrake .NET Bug Handler, offering real-time alerts and instantaneous insight into what went wrong with your .NET code, along with built-in support for a variety of popular development integrations including: JIRA, GitHub, Bitbucket, and much more.