Five Common Exceptions When Building C# Applications and How to Avoid Them
1 May 2018 - 4 min read
Welcome back to this week's CodeUp article, where you can find valuable and practical tips to make your coding life easier. In today’s post, I will share with you five most common C# exceptions that you may run into when developing your application. I will also demonstrate via code examples how we can prevent them from happening. In case you are not 100% clear, "Exception" in C# means error that happens with your program. I hope reading this post will help to decrease the number of exceptions in your application :-).
#1 - NullReferenceExceptionThis is one of the most easily to produce exceptions. This exception will be thrown when you try to access property of a null object. For example, the code below will generate the
Because we try to access the
IMDBRatingproperty of the null
infinityWarobject, if this code runs our program will stop working. To fix this common error is quite simple, you just need to check whether the object is null or not before accessing its property. Below is the code rewritten:
#2 - InvalidOperationExceptionSimilar to NullReferenceException, InvalidOperationException can be thrown by .NET if we call an invalid method from an object.
With this code, we are trying to access the first item in the list of
Movieobjects. However, because the list has no element in it, calling the
First()extension method will return nothing. As a result, the second line of code will return the
InvalidOperationException: Sequence contains no element.
To prevent the exception, instead of using the
First()method, you can use
FirstOrDefault(). This method will return a
nullobject if the list has no item instead of throwing an exception.
Another way is you can check if the list has more than one item before accessing the first one. So our code will look like this:
#3 - IndexOutRangeException and ArguementOutOfRangeExceptionThese two are similar so I group them as one. When we try to access item in an array or list using index number, if the index is invalid, these exceptions will be thrown. Because we regularly add or remove items in arrays and collections in a typical program, they can happen quite often.
Let’s look at the error-bound code below:
The first two line of code will generate the
IndexOutOfRangeException. The code tries to access the fourth item in the array, which is invalid because it can only store three items at max. By the way, because array in C# has zero-based index, the first item will start with 0, so 3 will give you access to the fourth item.
Similarly, the other two lines of code will generate the
ArguementOutOfRangeExceptionas it tries to invoke item from an empty list.
To prevent these exceptions is quite simple, you just need to check whether the array or collection has at least X number of elements before accessing. For instance, the code below will check if the array and collection have at least four items before invoking the fourth one.
Alternatively, if you have a variable that stores index, you should check if the variable is smaller than the collection’s length like this:
if(index < moviesList.Count)before using it.
#4 - System.FormatExceptionIn real-world programming, this exception is typically thrown when our program is trying to convert a string value to a different data type but the string does not conform to the required pattern. For example, let’s take a look at a sample code extracted from an application in my C# Acceleration course.
This piece of code assigns the values retrieved from Excel spreadsheet’s cells to the
coolMovieobject’s properties. You can notice the third assignment statement parses the Excel cell’s string value to double type using the
Double.Parse()method. If the value is not numerical,
FormatExceptionwill be thrown because C# cannot covert a non-numerical value to
doubleis a common data type in C# to store floating point values). Because we cannot control the input value from Excel or other external data sources, you can imagine how easy it is to produce this exception.
The solution to this issue is replacing the
TryParse(). Here’s the modified code: We will need to supply the
TryParse()method with the string value and another variable that will take in the parsed value if successful. Then, we can safely assign the variable to the
outkeyword indicates that the
ratingvariable is passed by reference not value, which makes the change for
ratingvisible by the caller code.
Booleantype result (true or false) that you can evaluate to make the right decision in your code.
#5 - System.Net.WebExceptionThe last common exception that I often see is
System.Net.WebException. This one will occur when your program is trying to connect to a remote server which is not available. Here's the code with potential error: This code:
HttpWebResponse HttpWResp = (HttpWebResponse)req.GetResponse()will attempt to connect to the remote server and returns the response. If the URL is not available, then we will have for ourselves a
Because controlling the availability of a remote server is completely out of our hand, the only way we can do to save our application is to put the code in a
try catchblock. Let’s see how the code looks like now: You can see I have wrapped the block of code that connects to the remote server in a
try catchblock which I set up to catch the
System.Net.WebException. Inside the catch block, I'll write the exception details and time it occurs into a text-based log file. I can explore this file to find out more details about the issue later.
And there you have it, five most common exceptions in a typical program and how to prevent them. Feel me to email me about any particular topic you want to learn or feedback that you may have.
Thanks for reading and see you in next week's article! :-)
Tim Huynh, Founder of CodeStrengthen
Tim is also a Full-Stack developer and instructor at CodeStrengthen who is passionate about educating the future workforce.