C# Exception Handling: 3 Practical Examples

Explore three practical examples of C# exception handling using try-catch to manage errors effectively.
By Jamie

Understanding C# Exception Handling with try-catch

Exception handling is a critical aspect of programming that allows developers to manage errors gracefully. In C#, the try-catch block is commonly used to catch exceptions that may occur during the execution of a program. This ensures that the application can handle errors smoothly without crashing and provides a better user experience. Below, we present three practical examples of C# exception handling using try-catch, each demonstrating different contexts and use cases.

Example 1: File Reading with Error Handling

Use Case

This example demonstrates how to handle exceptions when attempting to read from a file. It’s common for file operations to fail due to various reasons, such as the file not existing or lacking the necessary permissions.

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string filePath = "example.txt";

        try
        {
            string content = File.ReadAllText(filePath);
            Console.WriteLine(content);
        }
        catch (FileNotFoundException e)
        {
            Console.WriteLine("Error: File not found.\n" + e.Message);
        }
        catch (UnauthorizedAccessException e)
        {
            Console.WriteLine("Error: Access denied to file.\n" + e.Message);
        }
        catch (Exception e)
        {
            Console.WriteLine("An unexpected error occurred: \n" + e.Message);
        }
    }
}

Notes

  • The example uses multiple catch blocks to handle specific exceptions, providing tailored error messages based on the situation.
  • The catch-all exception block at the end ensures that any unexpected errors are also captured and reported.

Example 2: Database Connection Handling

Use Case

This example illustrates how to manage exceptions when connecting to a database. It’s essential to handle connection-related errors, such as network issues or invalid connection strings, to prevent the application from crashing.

using System;
using System.Data.SqlClient;

class Program
{
    static void Main()
    {
        string connectionString = "your_connection_string_here";

        try
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                connection.Open();
                Console.WriteLine("Connection opened successfully.");
            }
        }
        catch (SqlException e)
        {
            Console.WriteLine("Database connection error: \n" + e.Message);
        }
        catch (Exception e)
        {
            Console.WriteLine("An unexpected error occurred: \n" + e.Message);
        }
    }
}

Notes

  • The using statement ensures that the database connection is properly disposed of, even if an exception occurs.
  • Specific exceptions related to SQL operations are caught to provide more meaningful feedback.

Example 3: Parsing User Input

Use Case

In this example, we handle exceptions when parsing user input, which can often lead to errors if the input format is incorrect. This is a common scenario in applications that rely on user data.

using System;

class Program
{
    static void Main()
    {
        Console.WriteLine("Enter a number:");
        string userInput = Console.ReadLine();

        try
        {
            int number = int.Parse(userInput);
            Console.WriteLine($"You entered: {number}");
        }
        catch (FormatException e)
        {
            Console.WriteLine("Error: Invalid input format. Please enter a valid number.\n" + e.Message);
        }
        catch (OverflowException e)
        {
            Console.WriteLine("Error: Number is too large or too small.\n" + e.Message);
        }
        catch (Exception e)
        {
            Console.WriteLine("An unexpected error occurred: \n" + e.Message);
        }
    }
}

Notes

  • This example uses int.Parse, which can throw exceptions for invalid formats. The specific exceptions for format and overflow are handled separately to inform the user accurately.
  • Validating user input before parsing can further improve the robustness of the application.

In conclusion, these examples of C# exception handling with try-catch illustrate the importance of managing errors effectively in various programming scenarios. Proper exception handling not only prevents application crashes but also enhances user experience by providing clear feedback on issues.