Try catch finally in C#

The try..catch..finally block in .NET allows developers to handle runtime exceptions. The syntax has three variations, try..catch, try..finally, and try..catch..finally. Learn more here: Exception Handling in C#
 
The code example shows a try catch finally block syntax. 
  1. try  
  2. {  
  3. //Put suspected code here. When an exception occurs, the control will move to the catch block
  4. }  
  5. catch  
  6. {  
  7. //Catch the exception  
  8. }  
  9. finally  
  10. {  
  11. //this block of code will always get executed whether an  
  12. // exception occurs or not as long as there are no exceptions  
  13. // within this block itself. If an Exception is thrown here  
  14. // some outer try block should handle it  
  15. //Any Clean up code goes here. Especially to release any  
  16. //system resources such as file handles and network  
  17. //connections  
  18. }  
Let's go through an example so that we can better understand the purpose of the finally block. The following code illustrates the use of the finally block to clean up file states. 
  1. namespace TestFinally  
  2. {  
  3. using System;  
  4. using System.IO;  
  5. /// <summary>  
  6. /// Summary description for TestFinally.  
  7. /// </summary>  
  8. public class TestFinally  
  9. {  
  10. public TestFinally()  
  11. {  
  12. // TODO: Add Constructor Logic here  
  13. }  
  14. public static void Main()  
  15. {  
  16. StreamReader sr1 = null;  
  17. StreamWriter sw1 = null;  
  18. try  
  19. {  
  20. System.Console.WriteLine("In try block");  
  21. //Open files  
  22. sr1 = new StreamReader(File.Open("Test1.txt",  
  23. System.IO.FileMode.Open));  
  24. sw1 = new StreamWriter(File.Open("Test2.txt",  
  25. System.IO.FileMode.Append,  
  26. FileAccess.Write));  
  27. while (sr1.Peek() != -1)  
  28. {  
  29. sw1.WriteLine(sr1.ReadLine());  
  30. }  
  31. goto MyLabel;  
  32. }  
  33. catch (Exception e)  
  34. {  
  35. Console.WriteLine(String.Concat(e.Message,  
  36. e.StackTrace));  
  37. }  
  38. finally  
  39. {  
  40. //Int32 j ;  
  41. //j=0;  
  42. //j=j/5;  
  43. //If an Exception is thrown here some outer  
  44. //try block should handle it. The finally block  
  45. // will not be completely executed  
  46. Console.WriteLine("In finally block");  
  47. //we need to make sure that Close method of the  
  48. //Streamreader sr1 or StreamWriter sw1  
  49. //is called irrespective of whether an exception  
  50. // occurs or not  
  51. //to release any system resources associated with  
  52. //the reader or writer  
  53. if (sr1 != null)  
  54. {  
  55. sr1.Close();  
  56. }  
  57. if (sw1 != null)  
  58. {  
  59. sw1.Close();  
  60. }  
  61. }  
  62. MyLabel:  
  63. Console.WriteLine("In Mylabel");  
  64. // note: the following statements are not allowed  
  65. //inside a finally block:  
  66. //return, goto, break and continue  
  67. Console.ReadLine();  
  68. }  
  69. }  
  70. }  
In the above code, inside the Main method, we opened two files. First we opened the Test1.txt using a StreamReader object by passing a FileStream object returned by the File.Open method, and then we opened Test2.txt through a StreamWriter object by passing a FileStream object returned by the File.Open method. The intention here is to copy lines of Test1.txt and append them to Test2.txt. If the code in the try block executes successfully, we want to close StreamReader sr1 and StreamWriter sw1 so that system resources associated with the reader/writer are released.
 
If Test1.txt opens successfully but for some reason there is an exception thrown while opening Test2.txt, we still want to close the stream associated with Test1.txt. So in this example we have added the close methods in the finally code block so that they can be positively executed. We are checking for a null value because if none of the files is opened, we would get a nulldereferencing exception in the finally block.
 
Conclusion
 
Hope this article helped you understand how to use the try..catch..finally block in C#.  
 
Learn more here: Exception Handling in C# 
 
A detailed article on C# Try Catch  
 


Similar Articles