Using Await in Catch and Finally Blocks: A New Feature of C# 6.0

Introduction

On November 12, 2014, the day of the Visual Studio Connect() event, Microsoft announced Visual Studio 2015 Preview with many new and exciting features for developers for testing purposes. Microsoft announced the new version of C#, C# 6.0 that came with many improvements and new features. One of the newly introduced features of C# 6.0 is await in catch and finally blocks.

Don't forget to read my previous posts on this series "A new feature of C# 6.0".

What do we mean by using await in catch {} and finally {} block?

In C# 5.0 we can easily use try, catch, and finally blocks together but were unable to use async and await with catch {} and finally {} blocks due to implementation-specific issues in the C# compiler, but with the release of C# 6.0, our dream came true. Now finally we can use await statements and async methods with catch {} and finally {} blocks without writing complicated code. The compiler will handle this automatically. Let's have a look at the life cycle of try, catch and finally blocks before proceeding further.

  • try: The try block encloses the statements that might throw an exception.
  • catch: The catch block handles the exceptions thrown by the try block.
  • finally: It is an optional block and is always executed.

Block diagram

According to the MSDN, the await operator is applied to a task in an asynchronous method to suspend the execution of the method until the awaited task is completed. The asynchronous method in which await is used must be modified by the async keyword.

Today the use of async methods is very common. While working with async and await, we may have experienced that we want to put some of the results awaiting either in a catch block or in a final block or maybe in both, but thanks to Microsoft now we can easily do this with C# 6.0.

The following code snippet will show us how to call the await for async operations in catch {} and finally {} blocks.

try
{
    throw new Exception();
}
catch
{
    await Task.Delay(1000); // using await in catch block
}
finally
{
    await Task.Delay(1000); // using await in finally block
}

Demo Application using Visual Studio 2015 Preview.

using System;
using System.Threading.Tasks;
using System.IO;
using static System.Console;

namespace CSharpFeatures
{
    public class awaitincatchandfinally
    {
        public static void Main(string[] args)
        {
            FileRead fr = new FileRead();
            WriteLine(" Class Object Created Successfully!\n");
            fr.filreadoperation();
            ReadKey();
        }
    }
    public class FileRead
    {
        public async void filreadoperation()
        {
            try
            {
                StreamReader sr = File.OpenText("D:\\data.txt");
                WriteLine(" The first line of the file is: \{sr.ReadLine()}");
                sr.Close();
            }
            catch { await FileNotFound(); }
            finally { await ExitProgram(); }
        }
        private async Task FileNotFound()
        {
            WriteLine(" File not found. Please check the file name and file location.");
        }
        private async Task ExitProgram()
        {
            WriteLine("\n Press any key to exit");
        }
    }
}

Output

When there is no exception.

Output

When the exception occurs.

File not found

More examples are in the attached Zip file.

Summary

In this article, we learned how to use await statements with catch {} and finally {} blocks without writing any complicated code. This feature was in the list of much-demanded features by developers. Don't forget to read my other articles on the series "A new feature of C# 6.0". Share your opinion about this feature and how you will use it in your project. Your comments are most welcome. Happy Coding!


Similar Articles