What is Exceptions Try Catch With Example Code

Exceptions in C# provide a mechanism for handling errors and exceptional situations
that occur during the execution of a program. The try...catch block is used
to catch and handle exceptions gracefully, preventing the program from crashing.



using System;
 
class Program
{
    static void Main(string[] args)
    {
        try
        {
            // Attempt to perform some operation that might throw an exception
            int result = Divide(10, 0);
            Console.WriteLine("Result of division: " + result); // This line will not execute if an exception occurs
        }
        catch (DivideByZeroException ex)
        {
            // Handle the specific exception type (DivideByZeroException)
            Console.WriteLine("Error: " + ex.Message);
        }
        catch (Exception ex)
        {
            // Handle any other type of exception
            Console.WriteLine("An error occurred: " + ex.Message);
        }
 
        Console.WriteLine("Program continues after exception handling."); // This line will execute regardless of whether an exception occurred
    }
 
    static int Divide(int dividend, int divisor)
    {
        // Attempt to divide two numbers
        return dividend / divisor; // This line may throw a DivideByZeroException
    }
}