A Comprehensive Resource for Microsoft Technologies

Welcome, your go-to destination for everything related to .NET and Microsoft technologies. With over 10 years of experience in the IT industry, I am excited to share my knowledge and insights on this platform. This blog is dedicated to providing valuable information, tips, and tutorials that are not only relevant to the rapidly evolving IT industry but also essential for individuals working on real-time projects and preparing for interviews

C# Tutorial 8.1: Exception Handling (try, catch, finally)

 Exception handling is a crucial aspect of programming, and in C#, it is done using the try, catch, and finally blocks. These blocks help you manage and respond to errors gracefully. Here's a basic tutorial on C# exception handling:

1. Try-Catch Blocks:

The try block encloses the code that might throw an exception. If an exception occurs inside the try block, it's caught by the corresponding catch block.

try
{
    // Code that might throw an exception
}
catch (ExceptionType1 ex1)
{
    // Handle ExceptionType1
}
catch (ExceptionType2 ex2)
{
    // Handle ExceptionType2
}
// You can have multiple catch blocks for different exception types.
catch (Exception ex)
{
    // Handle other exceptions
}
  • Example:
try
{
    int x = 10;
    int y = 0;
    int result = x / y; // This will throw a DivideByZeroException
}
catch (DivideByZeroException ex)
{
    Console.WriteLine("Cannot divide by zero!");
}
catch (Exception ex)
{
    Console.WriteLine($"An error occurred: {ex.Message}");
}

2. Finally Block:

The finally block contains code that will always be executed, whether an exception is thrown or not. It is useful for cleanup operations.

try
{
    // Code that might throw an exception
}
catch (Exception ex)
{
    // Handle the exception
}
finally
{
    // Code that always executes, regardless of whether an exception occurred
}
  • Example:
FileStream file = null;
try
{
    file = new FileStream("example.txt", FileMode.Open);
    // Code to read from the file
}
catch (IOException ex)
{
    Console.WriteLine($"An IO error occurred: {ex.Message}");
}
finally
{
    // Ensure the file is closed, whether there was an exception or not
    file?.Close();
}

3. Throwing Exceptions:

You can manually throw exceptions using the throw keyword. This can be useful when you want to handle specific cases in your code.

try
{
    // Code that might throw an exception
    if (someCondition)
    {
        throw new CustomException("This is a custom exception");
    }
}
catch (CustomException ex)
{
    Console.WriteLine($"Custom exception caught: {ex.Message}");
}

4. Exception Properties:

Exceptions have properties that provide information about the exception, such as the message, stack trace, inner exception, etc.

try
{
    // Code that might throw an exception
}
catch (Exception ex)
{
    Console.WriteLine($"Exception Message: {ex.Message}");
    Console.WriteLine($"Stack Trace: {ex.StackTrace}");
    // You can access other properties like InnerException, Source, etc.
}

Conclusion:

Exception handling is crucial for writing robust and reliable code. It allows you to gracefully handle errors and provide meaningful feedback to users or log relevant information for debugging purposes. Remember to catch specific exceptions and handle them appropriately, and use the finally block for cleanup operations.