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.
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);
}
}
}
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);
}
}
}
using
statement ensures that the database connection is properly disposed of, even if an exception occurs.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);
}
}
}
int.Parse
, which can throw exceptions for invalid formats. The specific exceptions for format and overflow are handled separately to inform the user accurately.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.