Try Catch Finally Implementation In C#

Try Catch Finally Implementations

Add any code statements that might throw an exception in try block and add code statements used to handle the exception in catch block.

The finally block will execute always no matter what condition cause in try and catch blocks.

It's not mandatory to have finally block. The main purpose to have finally block is to release the system resources.

Create new console application by following steps.

Try Catch Finally Implementation In C#

Select console application.

Try Catch Finally Implementation In C#

Add the following code to read data from the file by using stream reader.

try {
    using(StreamReader sr = File.OpenText("content.txt")) {
        Console.WriteLine("Content of the file");
        Console.WriteLine(sr.ReadLine());
    }
} catch (Exception ex) {
    Console.WriteLine(ex.Message);
}
Console.ReadLine();

Try Catch Finally Implementation In C#

We can use multiple catch blocks to capute the errors .some of inbuilt exception classes are available ..ex:-DevidedByZero,FileNotFoundException,DirectoryNotFound.,etc

Added the code using some inbuilt exception classes,

try {
    using(StreamReader sr = File.OpenText("content.txt")) {
        Console.WriteLine("Content of the file");
        Console.WriteLine(sr.ReadLine());
    }
} catch (FileNotFoundException ex) {
    Console.WriteLine("The file was not found: " + ex.Message);
} catch (DirectoryNotFoundException ex) {
    Console.WriteLine("The directory was not found: " + ex.Message);
} catch (IOException ex) {
    Console.WriteLine("The file could not be opened: " + ex.Message);
} catch (Exception ex) {
    Console.WriteLine(ex.Message);
}
Console.ReadLine();

Try Catch Finally Implementation In C#

Conclusion

Hope this blog helped you understand how to use try, catch, and finally blocks in C#.

Next Recommended Reading Impact of Try-Catch on Performance