Reading files with Exceptions

Summary

In this tutorial, we are going to read text out of a file and handling exceptions in the program.

Exception occur during the runtime of the program.

For example, trying to read a file which doesn't exist or converting user input (string) into an integer when the user input contains other chars than digits.

Coding

First, we create a text file called "Example.txt" which we are going to read from our program.

To work with files, we need the "using System.IO;"

The "Files" class includes a method called "ReadAllText" which read the entire text file as one string.

To read the file, the code should look like this:

class Program
{
static void Main(string[] args)
{
string content = File.ReadAllText(@"C:\Lesson22\Exampl.txt");
Console.WriteLine(content);
Console.ReadLine();
}
}

Note: The "@" symbol before the string means that the "\" is not a command for the system but a char.

Please notice that the path to the file is incorrect. This is because we want to produce an exception.

Running the program would lead to an exception because the text file can't be found.

Because of this, our program stops working. We will now implement the try-catch-block in order to catch the exception.

Between the brackets of the try-block stand the code which can produce an exception.

If an exception is thrown in the try-block, then the catch-block will catch the exception and runs the code from the catch-block.

Moving our written code (for reading the file) into the try-block will look like this:

class Program
{
static void Main(string[] args)
{
try
{
string content = File.ReadAllText(@"C:\Lesson22\Exampl.txt");
Console.WriteLine(content);
Console.ReadLine();
}
catch
{

}
}
}

Running the application would lead to an opening and closing console. This is because the first line in the try-block throws an exception and calls the catch-block which doesn't contain any code.

In order to call the ReadLine every time no matter if an exception is thrown or not, we move it beneath the try-catch-block.

The catch-block can act differently for each exception type. For this we only need to specify the exception type for the catch-block.

The "Exception" type would catch all exceptions of each type and for example the "NullPointerException" would only catch Exceptions of the type "NullPointer".

These exception objects have variables which contain the exception message.

try
{
string content = File.ReadAllText(@"C:\Lesson22\Exampl.txt");
Console.WriteLine(content);
}
catch (Exception ex)
{
Console.WriteLine("Da war ein Problem!");
Console.WriteLine(ex.Message);
}
Console.ReadLine();

By moving the cursor to the ReadAllText method, a small window will appear. This window lists all types of exceptions that can be thrown from that method.

These exceptions are only thrown in special cases.

Implementing multiple catch-blocks has the advantage of reacting to each exception type differently.

So we can print another message into the console if the file was not found or the directory doesn't exist.

try
{
string content = File.ReadAllText(@"C:\Lesson22\Exampl.txt");
Console.WriteLine(content);
}
catch (FileNotFoundException ex)
{
Console.WriteLine("Da war ein Problem!");
Console.WriteLine("Gehe sicher, dass die Datei richtig benannt ist: Exampl.txt");
}
catch (DirectoryNotFoundException ex)
{
Console.WriteLine("Da war ein Problem!");
Console.WriteLine(@"Gehe sicher, dass der Ordner C:\Lesson22 existiert");
}
catch (Exception ex)
{
Console.WriteLine("Da war ein Problem!");
Console.WriteLine(ex.Message);
}
Console.ReadLine();

The finally-block can be optionally added after the catch-blocks. The finally-block will always be called after the try-catch-block.

It is mostly used to close database connections.

finally
{
// Code to finalize
// Setting objects to null
// Closing database connections
Console.WriteLine("Closing application now . . .");
}
Console.ReadLine();

Complete program code:

class Program
{
static void Main(string[] args)
{
try
{
string content = File.ReadAllText(@"C:\Lesson22\Exampl.txt");
Console.WriteLine(content);
}
catch (FileNotFoundException ex)
{
Console.WriteLine("Da war ein Problem!");
Console.WriteLine("Gehe sicher, dass die Datei richtig benannt ist: Exampl.txt");
}
catch (DirectoryNotFoundException ex)
{
Console.WriteLine("Da war ein Problem!");
Console.WriteLine(@"Gehe sicher, dass der Ordner C:\Lesson22 existiert");
}
catch (Exception ex)
{
Console.WriteLine("Da war ein Problem!");
Console.WriteLine(ex.Message);
}
finally
{
// Code to finalize
// Setting objects to null
// Closing database connections
Console.WriteLine("Closing application now . . .");
}
Console.ReadLine();
}
}