🔍What are Exceptions?

<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>

⚠️Common Causes of Exceptions

🛠️Exception Handling Tools

C# provides four main tools for handling exceptions:

1. Try Block

Contains the code that might throw an exception:

try
{
    // Code that might cause an exception
    string content = File.ReadAllText("myfile.txt");
}

2. Catch Block

Handles the exception if one occurs:

try
{
    string content = File.ReadAllText("myfile.txt");
}
catch (FileNotFoundException ex)
{
    Console.WriteLine($"Error: {ex.Message}");
}

3. Finally Block

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
}

4. Throw Keyword