C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Tip: This can be useful in some programs. The following program shows the FileNotFoundException being raised.
Main: The contents of the Main method are wrapped in an exception-handling construct.
And: The try block is executed. The file does not exist, so the runtime allocates a FileNotFoundException and searches the catch statements.
TryC# program that throws FileNotFoundException
using System;
using System.IO;
class Program
{
static void Main()
{
try
{
// Read in nonexistent file.
using (StreamReader reader = new StreamReader("not-there.txt"))
{
reader.ReadToEnd();
}
}
catch (FileNotFoundException ex)
{
// Write error.
Console.WriteLine(ex);
}
}
}
Output
System.IO.FileNotFoundException: Could not find file '...'
However: If you do not know if the file exists, it is often better use the File.Exists method.
Tip: The Exists method is a static method that returns a Boolean value, allowing you to avoid the FileNotFoundException.