Lesson 56 - Understanding Exception Handling

Tutorial Series: Free C# Fundamentals via ASP.NET Web Apps

Previous Article  |  Next Article


Get GitHub Code

In this lesson, we're going to talk about Exception Handling, which is a way of anticipating potential errors in your code and accounting for them. There are two basic types of errors you can encounter in programming, and they are:

  • Compilation errors.

  • Runtime errors.

Step 1: Understanding Compilation vs Runtime Errors

Compilation errors are the most common and they are readily visible and relatively easy to correct. Basically, whenever the compiler refuses to run your application – whether you missed an essential syntax element, or tried to write an invalid operation – the compiler catches it and forces you to change it before it can even run the app. Runtime errors, on the other hand, occur in the form of exceptions that are raised while your application is already running. These errors cannot be caught by the compiler and, for that reason, can be much more difficult to track down. The Exception might be raised due to a variety of reasons, from a conditional block that can’t perform, to attempting to operate on data that can't be parsed, to unsanitized user-input. These kinds of runtime errors are usually found through rigorous testing, running the application under many different conditions. However, there are other kinds of errors that a developer may not always be able to account for. For example, an Exception could also occur as a result of a dependency on some external system that the developer has no control over. An application may depend on a database server, a network server, a web service, something in the file system, and so on. These resources sometimes experience outages, or are just not available at the moment when the application needs them.

Step 2: Understanding When to Employ Exception Handling

Exception Handling comes into play when a developer can’t account for a possible Exception, and yet doesn’t want the Exception to cause the entire app to crash. This “graceful degradation” can be accounted for – mitigating the impact on the user – by implementing structured Exception Handling, or “fail-safes” in the code. Unhandled Exceptions are those that are not accounted for and will result in the application terminating in some ungraceful way. If we're running in Debug mode, the environment will stop and switch from the web browser to Visual Studio, such as with this Overflow Exception we saw in lesson 009 when we tried to calculate, and store, a number larger than an int is allowed to hold:


cs-asp-056---understanding-exception-handling.001


Step 3: The “Yellow Screen of Death”

If we weren't in Debug mode, but were running the application in a live environment when an unhandled exception occurs, the end user would see what developers call “The Yellow Screen of Death,” which is essentially an error page that contains information meant for the developer, not the end user:


cs-asp-056---understanding-exception-handling.002


Step 4: Try, Catch, and Finally Components of Exception Handling

Normally, we would want to account for these Exceptions with either a Global Exception Handler (which we will look at in the next lesson) or a Local Exception Handler that is written directly in the block of code that might cause the Exception in question. These Exceptions are handled via a series of code blocks reminiscent of if() conditionals, taking the form of try, catch(), and finally:

  1. try represents the existing code that may cause the Exception.

  2. catch() represents what happens in the event of the Exception being raised.

  3. finally represents an action taken regardless of whether or not an Exception occurs.


cs-asp-056---understanding-exception-handling.003


It’s worth noting that – similar to the else if() clause, sandwiched in the middle of if() statements – you can have as many catch() statements as you need to handle different Exceptions that might be raised.

Step 5: Create a New Project

For this lesson, create a new ASP.NET project called “ExceptionHandling” and following the previous lesson’s steps, include two separate projects for ExceptionHandling.Domain, and ExceptionHandling.Web. The Web project will be a typical ASP.NET project with a Default.aspx file, while the domain project will be an ordinary class library with two custom classes called Character and GameActions, respectively:


cs-asp-056---understanding-exception-handling.004


Step 6: Set a Default Project as Application Entry Point

It’s important to set the ExceptionHandling.Web project as the default project, so whenever you run the app its code is run first as the entry point to the rest of your application. To do this, right-click on the ExceptionHandling.Web project in the Solution Explorer and select from the menu “Set as StartUp Project.” This highlights the project in bold within the Solution:


cs-asp-056---understanding-exception-handling.005


You will also need to add the Domain project as a reference to the Web project by right-clicking on “References” under ExceptionHandling.Web and selecting “Add Reference…”:


cs-asp-056---understanding-exception-handling.006


Choose the Domain project from the projects available via the current Solution:


cs-asp-056---understanding-exception-handling.007


Tip:

If you did not see this Reference available, be sure to first build the project by right-clicking on it and selecting “Build”:


cs-asp-056---understanding-exception-handling.008


The Web project will have the following Server Controls and programmatic IDs:

  1. heroNameTextBox

  2. heroHitPointsTextBox

  3. gamesWonTextBox

  4. totalGamesTextBox

  5. calculateButton

  6. resultLabel


cs-asp-056---understanding-exception-handling.009


Step 7: Create an Intentional Exception

The calculateButton_Click() method will simply output a decimal result of division between gamesWonTextBox and totalGamesTextbox, formatted as a win percentage:


ccs-asp-056---understanding-exception-handling.010
s-asp-056---understanding-exception-handling.010


Notice when you run the app, an Exception is raised if you try to divide by zero (this is because values of type decimal can’t be divided by zero):


cs-asp-056---understanding-exception-handling.011


cs-asp-056---understanding-exception-handling.012


Next, click on the “Continue” button:


cs-asp-056---understanding-exception-handling.013


This would result in a “Yellow Screen of Death” if not properly handled within the code. That wouldn’t be acceptable because it will not provide any helpful information that the user can then act on and could actually provide information that could be used maliciously through a hack. Nor would it produce a result that looks like the rest of the application or website. With that in mind, let’s try to handle this Exception by wrapping it within a Try/Catch. You can initialize the code snippet for this by typing in “try” and hitting tab twice on your keyboard:


cs-asp-056---understanding-exception-handling.014


Now when you run the application and try to produce the same Exception, you get the custom user-facing error message instead:


cs-asp-056---understanding-exception-handling.015


Step 8: Catching Generic and Specific Exceptions

The problem now is that the error message is too generic, and doesn’t anticipate the specific error and tell the user what they should do in order for the code to run properly. To combat this, you can simply add another catch() statement that executes a reaction specific to the anticipated error:


cs-asp-056---understanding-exception-handling.016


It’s important to note that order of catch() statements is important. The rule of thumb is to keep the most specific catch() statements above the generic ones. In the below example, the first catch occurs on basically any Exception that may occur, and since this Exception catches all possible exceptions, you will never even execute the more specific DivideByZeroException (hence the red underline):


cs-asp-056---understanding-exception-handling.017


Another, sometimes more elegant, way of handling many different Exceptions with the generic catch() is to reference the exact error message and store it as a variable. This allows you to then reference the exact exception that was caught and display it to the end user by accessing the Exception class' properties:


cs-asp-056---understanding-exception-handling.018


cs-asp-056---understanding-exception-handling.019


Step 9: Populate the Character and GameActions Classes

Let’s look at this a bit deeper by creating more code within our project. Start off by filling out the classes we created earlier in the Domain layer of our Solution:


cs-asp-056---understanding-exception-handling.020


cs-asp-056---understanding-exception-handling.021


And then add some code that references these Domain objects within the existing try statement in calculateButton_Click():


cs-asp-056---understanding-exception-handling.022


Step 10: Throwing an Exception

There’s an intentional problem in this code: the monster object is initialized with having zero HitPoints. When the battle sequence starts, with the call to GameActions.Battle(), we should create a way to throw our own handled Exception, because it shouldn’t be possible to battle an enemy that technically isn’t regarded as “currently alive” in the game logic. To accomplish this, write the following within the Battle() method:


cs-asp-056---understanding-exception-handling.023


What we’re essentially doing is forcing an Exception to be raised under a condition that we determine. We chose the ArgumentOutOfRangeException as it’s available to use via the .NET Framework and allows us to append a custom message as an input parameter to its constructor. Although we haven’t accounted for this specific Exception in the original Try/Catch, it will be caught by the generic Exception and will append our custom message to its existing message:


cs-asp-056---understanding-exception-handling.024


Step 10: Catching the Thrown Exception at Method Call

To make the error message more specific we can just add this particular Exception to the top of our catch() hierarchy:


cs-asp-056---understanding-exception-handling.025


It’s possible to create our own custom Exceptions which inherit from established Exceptions but are specific to the code we are creating. For instance, we could create a DefenderAlreadyDead Exception or an AttackerAlreadyDead Exception with error messages specific to those cases. We will be looking at this precise scenario in ensuing lessons.

We have yet to cover how to use the finally element in the Try/Catch sequence. This part executes no matter what happens in the Try/Catch and is usually used to implement “clean-up” code at the very end of the process. For example, if you had an open database connection you might put some code in the finally block that is responsible for closing all open connections, freeing up that resource. This will become more important once we work with external resources, so for now just keep that rule of thumb in mind.


Tip:

Exception Handling is extremely useful, but don’t take it for granted! There was a time, back in the days when procedural programming dominated, when programmers would return integer values from method calls to represent the success or failure of that particular method call. It was a very archaic system that was difficult to consistently implement and was often cryptic to the user and even the developer!

Step 11: Understanding Where and When To Use Exception Handling

At this point, it’s natural to ask where and when you should use Try/Catch Exception Handling in your code. The rule of thumb here is to employ it wherever you have code that you have no control over, such as an external resource or user-determined input. When it comes to user input, it is still preferable to validate against known problems within the code itself. For example, if we require a numerical value entered by the user but we know the user might enter a string that can be validated in the code through simple evaluations, or even by using built-in validation Server Controls. However, you will still probably want to use some Exception handling here as its unlikely you will be able to account for all possible user-input (even if you are confident you know every possible permutation ahead of time).

Also, ideally you would wrap Exceptions around only the code that might throw the Exception rather than entire blocks of code. You should also wrap Try/Catch around method calls that are known to throw Exceptions, such as in the attacker/defender example above. The final bit of advice on employing Exception Handling is to log each Exception so that you, the developer, can peer into the problems that users are experiencing without them having to even contact you and try to describe it for you. There are many ways that you can save the Exception data into a of log file, and although that is outside of the scope of this lesson you should be aware of its importance as you delve deeper into the subject matter.


Related Articles in this Tutorial:

Lesson 1 - Series Introduction

Lesson 2 - Installing Visual Studio 2015

Lesson 3 - Building Your First Web App

Lesson 4 - Understanding What You Just Did

Lesson 5 - Working with Projects in Visual Studio

Lesson 6 - Simple Web Page Formatting in Visual Studio

Challenge 1

Solution 1

Lesson 7 - Variables and Data Types

Lesson 8 - Data Type Conversion

Lesson 9 - Arithmetic Operators

Lesson 10 - C# Syntax Basics

Challenge 2 - ChallengeSimpleCalculator

Solution - ChallengeSimpleCalculator

Lesson 11 - Conditional If Statements

Lesson 12 - The Conditional Ternary Operator

Challenge 3 - ChallengeConditionalRadioButton

Solution - Challenge Conditional RadioButton

Lesson 13 - Comparison and Logical Operators

Lesson 13 Challenge - First Papa Bob's Website

Solution - Challenge First Papa Bob's Website

Lesson 14 - Working with Dates and Times

Lesson 15 - Working With Spans of Time

Lesson 16 - Working with the Calendar Server Control

Challenge 4 - Challenge Days Between Dates

Solution - Challenge Days Between Dates

Lesson 17 - Page_Load and Page.IsPostBack

Lesson 18 - Setting a Break Point and Debugging

Lesson 19 - Formatting Strings

Challenge 5 - Challenge Epic Spies Assignment

Solution - Challenge Epic Spies Assignment

Lesson 20 - Maintaining State with ViewState

Lesson 21 - Storing Values in Arrays

Lesson 22 - Understanding Multidimensional Arrays

Lesson 23 - Changing the Length of an Array

Challenge 6 - Challenge Epic Spies Asset Tracker

Solution - Challenge Epic Spies Asset Tracker

Lesson 24 - Understanding Variable Scope

Lesson 25 - Code Blocks and Nested If Statements

Lesson 26 - Looping with the For Iteration Statement

Challenge 7 - Challenge For Xmen Battle Count

Solution - Challenge For Xmen Battle Count

Lesson 27 - Looping with the while() & do...while() Iteration Statements

Lesson 28 - Creating and Calling Simple Helper Methods

Lesson 29 - Creating Methods with Input Parameters

Lesson 30 - Returning Values from Methods

Lesson 31 - Creating Overloaded Methods

Lesson 32 - Creating Optional Parameters

Lesson 33 - Creating Names Parameters

Lesson 34 - Creating Methods with Output Parameters

Challenge 8 - Challenge Postal Calculator Helper Methods

Solution - Challenge Postal Calculator Helper Methods

Mega Challenge Casino

Solution - Mega Challenge Casino

Lesson 35 - Manipulating Strings

Challenge 9 - Phun With Strings

Solution - Challenge Phun With Strings

Lesson 36 - Introduction to Classes and Objects

Challenge - Hero Monster Classes Part 1

Solution - Hero Monster Classes Part 1

Challenge - Hero Monster Classes Part 2

Solution - Challenge Hero Monster Classes Part 2

Lesson 37 - Creating Class Files Creating Cohesive Classes and Code Navigation

Lesson 38 - Understanding Object References and Object Lifetime

Lesson 39 - Understanding the .NET Framework and Compilation

Lesson 40 - Namespaces and Using Directives

Lesson 41 - Creating Class Libraries and Adding References to Assemblies

Lesson 42 - Accessibility Modifiers, Fields and Properties

Lesson 43 - Creating Constructor Methods

Lesson 44 - Naming Conventions for Identifiers

Lesson 45 - Static vs Instance Members

Challenge 10 - Challenge Simple Darts

Solution - Challenge Simple Darts

Lesson 46 - Working with the List Collection

Lesson 47 - Object Initializers

Lesson 48 - Collection Initializers

Lesson 49 - Working with the Dictionary Collection

Lesson 50 - Looping with the foreach Iteration Statement

Lesson 51 - Implicitly-Typed Variables with the var Keyword

Challenge 11 - Challenge Student Courses

Solution - Challenge Student Courses

Mega Challenge War

Solution - Mega Challenge War

Lesson 52 - Creating GUIDs

Lesson 53 - Working with Enumerations

Lesson 54 - Understanding the switch() Statement

Lesson 55 - First Pass at the Separation of Concerns Principle

Lesson 56 - Understanding Exception Handling

Lesson 57 - Understanding Global Exception Handling

Lesson 58 - Understanding Custom Exceptions

Lesson 59 - Creating a Database in Visual Studio

Lesson 60 - Creating an Entity Data Model

Lesson 61 - Displaying the DbSet Result in an ASP.NET GridView

Lesson 62 - Implementing a Button Command in a GridView

Lesson 63 - Using a Tools-Centric Approach to Building a Database Application

Lesson 64 - Using a Maintenance-Driven Approach to Building a Database Application

Lesson 65 - Creating a New Instance of an Entity and Persisting it to the Database

Lesson 66 - Package Management with NuGet

Lesson 67 - NuGet No-Commit Workflow

Lesson 68 - Introduction the Twitter Bootstrap CSS Framework

Lesson 69 - Mapping Enum Types to Entity Properties in the Framework Designer

Lesson 70 - Deploying the App to Microsoft Azure Web Services Web Apps

Papa Bob's Mega Challenge

Papa Bob's Mega Solution Part 1 - Setting up the Solution

Papa Bob's Mega Solution Part 2 - Adding an Order to the Database

Papa Bob's Mega Solution Part 3 - Passing an Order from the Presentation Layer

Papa Bob's Mega Solution Part 4 - Creating the Order Form

Papa Bob's Mega Solution Part 5 - Adding Enums

Papa Bob's Mega Solution Part 6 - Creating an Order with Validation

Papa Bob's Mega Solution Part 7 - Calculating the Order Price

Papa Bob's Mega Solution Part 8 - Displaying the Price to the User

Papa Bob's Mega Solution Part 9 - Creating the Order Management Page


Comments

Please login or register to add a comment