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{
// Code block
}catch (Exception e){
// Exception
}
finally{
// Code
}
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);
}
}
}
Shahzad
Sabri
Avatar
Index was outside the bounds of the array.
In C# we can use more the 1 try cache block for better understanding we will see below 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);
}
}
}
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