Card image cap
64x64

Tim Huynh

Five Common Exceptions When Building C# Applications and How to Avoid Them


1 May 2018 - 4 min read



Hello CodeUpers,

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 - NullReferenceException

This 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 NullReferenceException:

Movie infinityWar = null;
Console.WriteLine(infinityWar.IMDbRating);
Because we try to access the IMDBRating property of the null infinityWar object, 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:

Movie infinityWar = null;
//check whether the infinityWar object is null.
if(infinityWar != null)
{
    // If it is not null, then access the IMDbRating property
    Console.WriteLine(infinityWar.IMDbRating);
}

#2 - InvalidOperationException

Similar to NullReferenceException, InvalidOperationException can be thrown by .NET if we call an invalid method from an object.

List<Movie> movies = new List<Movie>();
Movie firstMovie = movies.First();
With this code, we are trying to access the first item in the list of Movie objects. 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 null object 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:

List movies = new List<Movie>();
if(movies.Count > 0)
{
    Movie firstMovie = movies.First();
}

#3 - IndexOutRangeException and ArguementOutOfRangeException

These 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:

Movie moviesArray = new Movie[3];
var movieA = moviesArray[3];

List<Movie> moviesList = new List<Movie>();
var movieB = moviesList[3];
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 ArguementOutOfRangeException as 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.

Movie moviesArray = new Movie[3];
if (moviesArray.Length >= 4)
{
    var movieA = moviesArray[3];
}

List<Movie> moviesList = new List<Movie>();
if (moviesList.Count >= 4)
{
    var movieB = moviesList[3];
}
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.FormatException

In 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.

Movie coolMovie = new Movie
{
    MovieName = wks.Cells[r, 1].Value.ToString(),
    Genre = wks.Cells[r, 2].Value.ToString(),
    IMDbRating = Double.Parse(wks.Cells[r, 3].Value.ToString())
};
This piece of code assigns the values retrieved from Excel spreadsheet’s cells to the coolMovie object’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, FormatException will be thrown because C# cannot covert a non-numerical value to double type (double is 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 Parse() method with TryParse(). Here’s the modified code:

double rating = 0;
Double.TryParse(wks.Cells[r, 3].Value.ToString(), out rating);
Movie coolMovie = new Movie
{
    MovieName = wks.Cells[r, 1].Value.ToString(),
    Genre = wks.Cells[r, 2].Value.ToString(),
    IMDbRating = rating
};
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 IMDbRating property. The out keyword indicates that the rating variable is passed by reference not value, which makes the change for rating visible by the caller code. TryParse() also returns Boolean type result (true or false) that you can evaluate to make the right decision in your code.

#5 - System.Net.WebException

The 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:
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://unavailableURL.com");
req.PreAuthenticate = true;
HttpWebResponse HttpWResp = (HttpWebResponse)req.GetResponse();
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 System.NET.WebException.

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 catch block. Let’s see how the code looks like now:
try
{
    HttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://unavailableURL.com");
    req.PreAuthenticate = true;

    HttpWebResponse HttpWResp = (HttpWebResponse)req.GetResponse();
}
catch (System.Net.WebException e)
{
    var logFilePath = "LogFolder\log.txt";
    using (StreamWriter file = new StreamWriter(logFilePath, true))
    {
       file.WriteLine($"[EXCEPTION DETAILS]: {e.ToString()}, [DATE]: {DateTime.Now}");
    }
}
You can see I have wrapped the block of code that connects to the remote server in a try catch block 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! :-)

Do you want to receive more lessons like this? Join Tim' Special Mailing List.

* indicates required

By joining, you also agree to the terms of use and privacy policy.


64x64

Author

Tim Huynh, Founder of CodeStrengthen

Tim is also a Full-Stack developer and instructor at CodeStrengthen who is passionate about educating the future workforce.