C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Tip: When we catch IOException, we do not need to detect other file-handling exceptions if they occur.
C# program that handles IOException
using System;
using System.IO;
class Program
{
static void Main()
{
try
{
File.Open("C:\\nope.txt", FileMode.Open);
}
catch (IOException)
{
Console.WriteLine("IO");
}
}
}
Output
IO
Tip: The exception types should be ordered from most derived to least derived. FileNotFoundException is more derived than IOException.
C# program that handles FileNotFoundException
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");
}
}
}
Output
Not found
Also: As with any derived class, you can use casts on IOException to determine its most derived type.
Casts: You can use the is-cast and the as-cast. The GetType method will return the most derived type as well.
IsAsGetTypeExample: We call the Directory.GetDirectories method on a directory that does not exist on the computer.
Thus: An exception is thrown and the program terminates. And no winning lottery tickets are acquired.
C# program that causes DirectoryNotFoundException
using System.IO;
class Program
{
static void Main()
{
Directory.GetDirectories("C:\\lottery-numbers\\");
}
}
Output
Unhandled Exception: System.IO.DirectoryNotFoundException:
Could not find a part of the path 'C:\lottery-numbers\'....