Thursday, April 7, 2016

Error & Exception Handling in C#

In today's blog post, I will be discussing error and exception handling in C#. We will also be discussing some new features of C# 6 for ways of exception handling.

Error & Exception Handling in C#

In order to make our application more resilient and robust, exception handling is inevitable. There could be several reasons for unforeseen errors in our application. Some times user might enter some bad data, some times some file may be missing, some times some server might be down, some times there might be division by zero and so on. If we don't have proper exception handling in place then our application might crash which certainly is not a nice user experience.

Try Catch Exception

If we have any potentially dangerous code which might throw exception, we can surround it by try block followed by a catch statement.
Here is a simple example:

try
{
       Console.WriteLine("Please Enter a number");
       var input = Console.ReadLine();
       var i = Convert.ToInt32(input);
       Console.WriteLine(String.Format("You entered number: {0}", i ));
}
catch (Exception e)
{
       Console.WriteLine("Number not valid.");
}
Console.ReadLine();

The code snippet asks user to input a number. If the number is valid then no exception is thrown. If the number is not valid, the code will throw an exception. Since we have a catch statement, we will get the output of number not being valid.

Here we had a generic exception handler which can handle any exception. If we want to have several exception handlers, each for several exception types, we can have those. We need to always have more specific exception type before less specific ones. These exception handlers are executed in order. As soon as the first match is found that catch block is executed.

Try Catch Finally

After the try block is executed, the catch exception block might be executed (if there was an exception), and then finally block is executed, if exists. The finally block is useful when we want to execute a block of code no matter if the exception occurred or not. This is useful if we open a file or database connection or something like that. We can close it as part of the finally block.

try
{
    //open connection
}
catch (Exception e)
{
    //handle exception
}
finally
{
    //close connection
}

Exception Filters

Suppose, we want to handle exception only if some specific condition satisfies. Otherwise, we don't want to handle the exception. Until C# 5, we had to do it this way:

try
{
      //Dangerous Code ;)
}
catch(Exception e)
{
     if(e.Message == "Message")
         //do something
     else
         throw;
}

So here we re-threw the exact same exception. The issue with this is that the stack trace is lost when we re-throw the exception. So we loose the information where the exception originally started.
In C# 6, we have exception filters which look like this:

try
{
      //Dangerous Code ;)
}
catch(Exception e) if(e.Message == "Message")
{
      //do something
}

This approach is much more cleaner and there is no re-throw of the exception, so no losing of stack trace.

Conclusion

Exception Handling is necessary for logging and better user experience. By examining these logs, we can improve the application performance too as exceptions generally slow down the application.

For future updates to my weekly blog, please subscribe to my blog via the "Subscribe To Weekly Post" feature at the right and follow me on Twitter. Until then Happy Coding :)

1 comment:

  1. I didn't know about the conditional catch block. Very cool.

    ReplyDelete