C# Try Catch Exception Handling: Complete Guide with Examples

C# Try Catch Exception Handling: Complete Guide with Examples

Try Catch in C# is a mechanism used to handle runtime errors (exceptions) so that the program can continue running or fail gracefully.

During program execution, unexpected errors such as dividing by zero, invalid input, or file access issues can occur. Exception handling in C# allows developers to manage these errors using try, catch, and optionally finally blocks. The try block contains code that may cause an exception, while the catch block handles the error. The finally block executes regardless of whether an exception occurred, making it useful for cleanup operations.

When is Try Catch Needed?

Use Try Catch when:

• Handling unpredictable runtime errors
• Working with file or network operations
• Validating user input
• Calling external APIs or services
• Ensuring application stability

How to Use Try Catch?

Basic Example

using System;

class Program
{
    static void Main()
    {
        try
        {
            int number = 10;
            int result = number / 0;
            Console.WriteLine(result);
        }
        catch (Exception ex)
        {
            Console.WriteLine("An error occurred: " + ex.Message);
        }
    }
}

Try Catch Finally Example

using System;

class Program
{
    static void Main()
    {
        try
        {
            Console.WriteLine("Starting operation...");
            int result = 10 / 0;
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error: " + ex.Message);
        }
        finally
        {
            Console.WriteLine("Execution completed.");
        }
    }
}

Specific Exception Handling

using System;

class Program
{
    static void Main()
    {
        try
        {
            int[] numbers = { 1, 2, 3 };
            Console.WriteLine(numbers[5]);
        }
        catch (IndexOutOfRangeException ex)
        {
            Console.WriteLine("Index error: " + ex.Message);
        }
        catch (Exception ex)
        {
            Console.WriteLine("General error: " + ex.Message);
        }
    }
}

Try Catch Flow Overview

Block Purpose Execution Condition
Try Code that may cause an exception Always executed first
Catch Handles the exception Executed only if error occurs
Finally Cleanup operations Always executed

Advantages and Disadvantages

Advantages Disadvantages
Prevents application crashes Can hide bugs if overused
Improves application stability Performance overhead if misused
Allows graceful error handling May lead to overly broad exception handling
Supports multiple exception types Requires careful design for proper use

Similar and Alternative Options

Option Description When to Use
Throw Exception Manually raises an error When custom error handling is needed
Result Codes Return status instead of exceptions Simple operations
Nullable Checks Prevents null reference errors Safer value handling
Validation Logic Pre-check input before execution Prevent exceptions early

Common Mistakes

• Using empty catch blocks that hide errors
• Catching generic Exception everywhere
• Not logging exceptions properly
• Overusing try-catch instead of validation
• Ignoring performance impact in critical loops
• Not using finally for resource cleanup

Contents related to 'C# Try Catch Exception Handling: Complete Guide with Examples'

C# Logging: Complete Guide to Logging Best Practices and Implementation
C# Logging: Complete Guide to Logging Best Practices and Implementation
C# Null Reference Exception: Causes, Fixes, and Best Practices
C# Null Reference Exception: Causes, Fixes, and Best Practices