File handling often causes errors. The .NET Framework throws exceptions. In this situation these are derived from the IOException
base class
.
For example, FileNotFoundException
can be treated as an IOException
. The IOException
type allows you to create more general catch clauses.
In this program, we cause a FileNotFoundException
to be thrown when the file does not exist. If the file cannot be opened, we get an IOException
.
IOException
, we do not need to detect other file-handling exceptions if they occur.using System;
using System.IO;
class Program
{
static void Main()
{
try
{
File.Open("C:\\nope.txt", FileMode.Open);
}
catch (IOException)
{
Console.WriteLine("IO");
}
}
}IO
We detect the possible FileNotFoundException
with a separate catch block. The IOException
block is only entered if another file handling exception is encountered.
FileNotFoundException
is more derived than IOException
.using System;
using System.IO;
class Program
{
static void Main()
{
try
{
File.Open("C:\\nope.txt", FileMode.Open);
}
catch (FileNotFoundException)
{
Console.WriteLine("Not found");
}
catch (IOException)
{
Console.WriteLine("IO");
}
}
}Not found
DirectoryNotFoundException
What could cause the DirectoryNotFoundException
? DirectoryNotFoundException
is a type of file handling exception. It is caused by a missing directory.
Directory.GetDirectories
method on a directory that does not exist on the computer.using System.IO;
class Program
{
static void Main()
{
Directory.GetDirectories("C:\\lottery-numbers\\");
}
}Unhandled Exception: System.IO.DirectoryNotFoundException:
Could not find a part of the path 'C:\lottery-numbers\'....
I opened mscorlib.dll
in IL Disassembler to find more about IOException
. I browsed to FileNotFoundException
and determined it is derived from IOException
.
class
, you can use casts on IOException
to determine its most derived type.is
-cast and the as
-cast. The GetType
method will return the most derived type as well.IOException
serves as the base class
for file handling exceptions. It is a useful abstraction for checking all such exceptions. It represents a subset of possible exceptions.