C# Exceptions – Try..Catch

Welcome to The Coding College! In this tutorial, we will explore exception handling in C# using the try, catch, and finally blocks. Exception handling is a crucial part of creating robust applications, as it ensures your program can handle unexpected situations gracefully.

What is an Exception?

An exception is an event that occurs during the execution of a program, disrupting its normal flow. Examples include:

  • Division by zero.
  • Attempting to access a file that does not exist.
  • Null reference errors.

In C#, exceptions are objects derived from the base class System.Exception.

Why Use Try…Catch?

The try...catch construct in C# allows you to handle runtime errors and prevent your program from crashing.

Syntax: Try…Catch

try
{
    // Code that may throw an exception.
}
catch (ExceptionType e)
{
    // Code to handle the exception.
}

Basic Example of Try…Catch

Example 1: Divide by Zero Exception

using System;

class Program
{
    static void Main()
    {
        try
        {
            int a = 10;
            int b = 0;
            int result = a / b; // This will throw a DivideByZeroException.
        }
        catch (DivideByZeroException e)
        {
            Console.WriteLine("Error: Cannot divide by zero!");
        }
    }
}

Output:

Error: Cannot divide by zero!

Handling Multiple Exceptions

You can use multiple catch blocks to handle different types of exceptions.

Example 2: Multiple Exceptions

using System;

class Program
{
    static void Main()
    {
        try
        {
            int[] numbers = { 1, 2, 3 };
            Console.WriteLine(numbers[5]); // This will throw an IndexOutOfRangeException.
        }
        catch (IndexOutOfRangeException e)
        {
            Console.WriteLine("Error: Index out of range!");
        }
        catch (Exception e)
        {
            Console.WriteLine("An error occurred: " + e.Message);
        }
    }
}

The Finally Block

The finally block is used to execute code that must run whether or not an exception occurs. This is useful for releasing resources like closing files or network connections.

Example 3: Try…Catch…Finally

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string path = "example.txt";
        StreamReader reader = null;

        try
        {
            reader = new StreamReader(path);
            Console.WriteLine(reader.ReadToEnd());
        }
        catch (FileNotFoundException e)
        {
            Console.WriteLine("Error: File not found!");
        }
        finally
        {
            if (reader != null)
            {
                reader.Close();
                Console.WriteLine("File closed.");
            }
        }
    }
}

Custom Exceptions

You can create custom exceptions by extending the Exception class.

Example 4: Custom Exception

using System;

class InvalidAgeException : Exception
{
    public InvalidAgeException(string message) : base(message) { }
}

class Program
{
    static void Main()
    {
        try
        {
            int age = -5;
            if (age < 0)
            {
                throw new InvalidAgeException("Age cannot be negative.");
            }
        }
        catch (InvalidAgeException e)
        {
            Console.WriteLine("Custom Exception: " + e.Message);
        }
    }
}

Best Practices for Exception Handling

  1. Catch Specific Exceptions: Always catch the most specific exception first to avoid masking issues.
  2. Avoid Swallowing Exceptions: Don’t leave catch blocks empty; at least log the error.
  3. Use Finally for Cleanup: Ensure resources are properly released in the finally block.
  4. Throw Exceptions Judiciously: Throw exceptions only for exceptional situations, not for normal program flow.
  5. Log Exceptions: Keep a log of exceptions for debugging and monitoring.

Common C# Exceptions

Exception TypeDescription
DivideByZeroExceptionAttempt to divide a number by zero.
IndexOutOfRangeExceptionAccessing an array element outside its bounds.
NullReferenceExceptionTrying to use an object that is null.
FileNotFoundExceptionAttempting to access a file that doesn’t exist.
InvalidOperationExceptionPerforming an invalid operation for an object’s state.

Conclusion

Exception handling is vital for building robust and error-resistant applications. By using try, catch, and finally effectively, you can gracefully handle errors and provide a better user experience.

Explore more C# tutorials and programming concepts on The Coding College. Keep learning and building error-free applications! 🚀

Leave a Comment