Exception Handling in C# (try...catch)

Exception: The code is defined as an event that occurs during the execution of a program that is unexpected by the program code. Exception handling is one of the most important concepts because it will handle all unwanted events or errors during program execution. In C# there are four keywords that be used in exception handling which are

  • try: We define the code in the try block which can throw an error.
  • catch: If try to throw an error catch block will handle the error.
  • finally: Finally block holds the default code block
  • throw: To throw an exception manually.

Syntax:

try{
      // Code block
}catch (Exception e){
      // Exception
}
finally{
   // Code 
}

Example:

using System;
class Program : System.Exception
{
    static void Main(string[] args)
    {
        string[] name = { "Shahzad", "Sabri", "Avatar" };
        for (int i = 0; i < name.Length; i++)
        {
            Console.WriteLine(name[i]);
        }
        try
        {
            //after the completion of for loop we are going in the try block with the wrong index number 
            Console.WriteLine(name[4]);
            //because index number is wrong so catch block will get the error information and show that error
        }
        catch (IndexOutOfRangeException e)
        {
            Console.WriteLine(e.Message);
        }
    }
}

Output:

Shahzad
Sabri
Avatar
Index was outside the bounds of the array.

Multiple try-catch blocks

In C# we can use more the 1 try cache block for better understanding we will see below example

Example:

using System;

class Program: System.Exception
{
    static void Main(string[] args)
    {
        string[] name = { "Shahzad", "Sabri", "Avatar" };
        for (int i = 0; i < name.Length; i++)
        {
            Console.WriteLine(name[i]);
        }
        try
        {
            try
            {
                Console.WriteLine(name[6]);
            }catch(Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            Console.WriteLine(name[4]);
        }
        catch (IndexOutOfRangeException e)
        {
            Console.WriteLine(e.Message);
        }
    }
}

Output:

Shahzad
Sabri
Avatar
System.IndexOutOfRangeException: Index was outside the bounds of the array.
   at Program.Main(String[] args) in C:\Users\PC\source\repos\ConsoleApp1\ConsoleApp1\Program.cs:line 16
Index was outside the bounds of the array.

In the above example, we are using nested try-catch block internal try-catch block will show the specific error message while internal try-catch block showing the complete error with line number where program getting the error