Exception Handling in C#

by mahidhar

Handling exceptions properly ensures your application can manage errors gracefully and continue running.

Try-Catch Blocks:

code
using System;

namespace NationalParks
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                string[] parks = { "Yellowstone", "Yosemite" };
                Console.WriteLine(parks[5]);
            }
            catch (IndexOutOfRangeException ex)
            {
                Console.WriteLine("Error: Index out of range. " + ex.Message);
            }
        }
    }
}

Custom Exceptions:

code
using System;

namespace NationalParks
{
    public class ParkNotFoundException : Exception
    {
        public ParkNotFoundException(string message) : base(message) { }
    }

    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                FindPark("Zion");
            }
            catch (ParkNotFoundException ex)
            {
                Console.WriteLine("Error: " + ex.Message);
            }
        }

        static void FindPark(string parkName)
        {
            string[] parks = { "Yellowstone", "Yosemite" };
            if (Array.IndexOf(parks, parkName) == -1)
            {
                throw new ParkNotFoundException($"Park '{parkName}' not found.");
            }
        }
    }
}

Best Practices:

Catch specific exceptions.
Avoid catching general Exception unless necessary.
Use custom exceptions for more meaningful error handling.
Always clean up resources in a finally block if needed.