(C# Language) Exceptions and Errors

A function throws an exception on failure. The functions that are expected to fail are written inside try blocks with one or more catch blocks. Each catch block handles a specific reason of failure. A catch block receives an exception object which is often used to obtain a detailed information of the cause of failure.
(Rev. 18-Jun-2024)

Categories | About |     |  

Parveen,

Table of Contents (top down ↓)

Example Program

We shall study the practical aspects of exception handling with a small program.

Create a C# console program with the latest version of .NET Core. Open the program.cs file. We shall use a FileStream to write some text to a file on the desktop.

Declare a FileStream instance fs.

Next create a path to the file on the desktop. The name of the file is "abc.txt".

We have used a try block to open a filestream to this file because the operation can fail if the file doesn't exist. Next we have used the Write function to write a byte array to this file.

A catch block is added to catch UnauthorizedAccessException and print an access denied message.



FileStream? fs = null;

String desktop = Environment.GetFolderPath(
                 Environment.SpecialFolder.DesktopDirectory);

String pathToFile = Path.Combine(desktop, "abc.txt");

try
{
  // fails if file doesn't exist 
  fs = new FileStream(pathToFile, 
                      FileMode.Open, 
                      FileAccess.Write);

  // write  a byte array  
  fs.Write(new byte[] {97, 98, 99});

}
catch(UnauthorizedAccessException e)
{
  Console.WriteLine($"Access denied - {e.Message}");

  return;
}
catch (FileNotFoundException e)
{
  Console.WriteLine($"File not found - {e.Message}");

  Console.WriteLine("Create abc.txt on desktop and retry.");

  return;
}
finally
{
  Console.WriteLine("Inside finally...");

  fs?.Close();
}

Console.WriteLine("Success!");



A second catch block has been added to catch FileNotFoundException exception. This exception is thrown if the file doesn't exist. Here also, we have printed a message to inform the user that the stream couldn't be opened because the file wasn't found.

A finally block has been added to close the filestream and dispose the instance. The finally block executes even if no exception is thrown. Hence, the filestream will be closed, regardless. We have added a message to inform if the finally block was entered and executed.

This is the general pattern of exception handling.

Video Explanation (see it happen!)

Please watch the following youtube video:

Run the Program

Let's test the program now. First make sure that there is no file called "abc.txt" on the desktop.


// ensure that there is no "abc.txt" file  
// on the desktop and run the program 

File not found - Could not find file '...Desktop\abc.txt'.
Create abc.txt on desktop and retry.

Inside finally...

Run the program! We verify that the program handles the FileNotFoundException and prints the exception message on the console. We also verify that the finally block is entered and executed.


// output if the file abc.txt exists 
// notice that the finally block executes now also 

Inside finally...
Success!

You can next create a file called "abc.txt" on the desktop and run the program. You will observe that the program succeeds and the finally block is executed in this case also.


This Blog Post/Article "(C# Language) Exceptions and Errors" by Parveen is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.