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 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.
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:
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:
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:
try represents the existing code that may cause the Exception.
catch() represents what happens in the event of the Exception being raised.
finally represents an action taken regardless of whether or not an Exception occurs.
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.
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:
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:
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…”:
Choose the Domain project from the projects available via the current Solution:
If you did not see this Reference available, be sure to first build the project by right-clicking on it and selecting “Build”:
The Web project will have the following Server Controls and programmatic IDs:
The calculateButton_Click() method will simply output a decimal result of division between gamesWonTextBox and totalGamesTextbox, formatted as a win percentage:
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):
Next, click on the “Continue” button:
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:
Now when you run the application and try to produce the same Exception, you get the custom user-facing error message instead:
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:
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):
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:
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:
And then add some code that references these Domain objects within the existing try statement in calculateButton_Click():
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:
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:
To make the error message more specific we can just add this particular Exception to the top of our catch() hierarchy:
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.
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!
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.
Lesson 56 - Understanding Exception Handling