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


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 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 was 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 complier 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 completes. The asynchronous method in which await is used must be modified by the async keyword.

    Today the use of async methods are 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 finally 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:

    1. try  
    2. {  
    3.     throw new Exception();  
    4. }  
    5. catch  
    6. {  
    7.     await Task.Delay(1000);  //using await in catch block  
    8. }  
    9. finally  
    10. {  
    11.     await Task.Delay(1000);  //using await in finally block  
    12. }  

    Demo Application using Visual Studio 2015 Preview

    1. using System;  
    2. using System.Threading.Tasks;  
    3. using System.IO;  
    4. using System.Console;  
    6. namespace CSharpFeatures  
    7. {  
    8.     public class awaitincatchandfinally  
    9.     {  
    10.         public static void Main(string[] args)  
    11.         {  
    12.             FileRead fr = new FileRead();  
    13.             WriteLine(" Class Object Created Successfully!\n");  
    14.             fr.filreadoperation();  
    15.             ReadKey();  
    16.         }  
    17.     }  
    18.     public class FileRead  
    19.     {  
    20.         public async void filreadoperation()  
    21.         {  
    22.             try  
    23.             {  
    24.                 StreamReader sr = File.OpenText("D:\\data.txt");  
    25.                 WriteLine(" The first line of the file is: \{sr.ReadLine()}");  
    26.                 sr.Close();  
    27.             }  
    28.             catch { await FileNotFound(); }  
    29.             finally { await ExitProgram(); }  
    30.         }  
    31.         private async Task FileNotFound()  
    32.         {  
    33.             WriteLine(" File not found. Please check the file name and file location.");  
    34.         }  
    35.         private async Task ExitProgram()  
    36.         {  
    37.             WriteLine("\n Press any key to exit");  
    38.         }  
    39.     }  
    40. }  


    When there is no exception:

    print firstine 

    When the exception occurs:

    file not found 

    More examples are in the attached Zip file.


    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!

    Up Next
      Ebook Download
      View all
      View all