Exception Handling in C#

Exception Handling in C#

 

Exception Handling in C#:- The C# try and catch keywords are used to define a try catch block. A try catch block is placed around code that could throw an exception. If an exception is thrown, this try catch finally blocks will handle the exception to ensure that the application does not cause an unhandled exception.

 

using System;

namespace usingcharp
{
  class Program
  {
    static void Main(string[] args)
    {
      try
      {
        int[] myNumbers = {10, 20, 40};
        Console.WriteLine(myNumbers[9]);
      }
      catch (Exception e)
      {
        Console.WriteLine("Something went wrong.");
      }  
      finally
      {
        Console.WriteLine("The 'try catch' is finished.");
      }  
    }
  }
}

 

The c# provides built-in support to handle the exception using trycatch & finally blocks.

 

try
{
    // put your code here that may raise exceptions
}
catch
{
    // handle exception here
}
finally
{
    // final cleanup code
}

2021-10-03