C# – Handling Exception – Try – Catch

Handling Exception using try-catch:

try block:

  • It is used to place the code that may raise exception.
  • When error occurs an exception object will be raised.

catch block:

  • Exception object raised in try block can be collected in catch block to handle.

Handling FormatException:

using System;
public class Program
{
	public static void Main(string[] args)
	{
		try{
			Console.WriteLine("Enter 2 integers to add : ");
			int a = Convert.ToInt32(Console.ReadLine());
			int b = Convert.ToInt32(Console.ReadLine());
			int c = a+b;
			Console.WriteLine("Result = " + c);
		}
		catch(FormatException){
			Console.WriteLine("Exception : Invalid input given");
		}
	}
}

Note : Catch block executes only if exception raises in try block.

IndexOutOfRangeException: Index was outside the bounds of the array.

using System;		
public class Program
{
	public static void Main(string[] args)
	{
		int[] arr = {10, 20, 30, 40, 50};
		Console.WriteLine(arr[5]);
	}
}

DivideByZeroException: Attempted to divide by zero

using System;		
public class Program
{
	public static void Main(string[] args){
		int a=10, b=0;
		int c=a/b;
		Console.WriteLine(c);
	}
}

NullReferenceException: Object reference not set to an instance of an object.

using System;		
public class Program
{
	public static void Main(string[] args){
		String s = null;
		int n = s.Length;
		Console.WriteLine(n);
	}
}
Scroll to Top