<aside>
Exceptions are errors that occur during program execution (runtime) that can disrupt the normal flow of a program. Without proper handling, these errors can cause your application to crash.
</aside>
C# provides four main tools for handling exceptions:
Contains the code that might throw an exception:
try
{
// Code that might cause an exception
string content = File.ReadAllText("myfile.txt");
}
Handles the exception if one occurs:
try
{
string content = File.ReadAllText("myfile.txt");
}
catch (FileNotFoundException ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
Contains code that always executes, regardless of whether an exception occurred:
FileStream file = null;
try
{
file = File.OpenRead("myfile.txt");
// Process file
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
finally
{
file?.Close(); // Always close the file
}