C# Exception

Exception handling is the way to handle the unexpected circumstances like runtime errors. So when the unexpected circumstance occurs, the program control is transferred to special functions known as handlers.

Syntax:

try{  
// the protected code. 
} 

Catch(Exception_Name){ 
// the code to run when unexpected circumstance occurs. 
} 

C++ EXCEPTION HANDLING KEYWORDS

  • try
  • catch, and
  • finally
  • throw
  1. try:-A try block identifies a set of lines of code for which particular exceptions will be activated. It’s followed by one or more catch blocks.
  2. throw:-A program throws an exception when a problem shows up. This is done using a throw keyword.

  3. finally:- It is the block of code that holds the default code.

  4. catch:-A program catches an exception with an exception handler at the place in a program where you want to handle the problem. The catch keyword indicates the catching of an exception.

// C# Program to show use of
// multiple try catch blocks
using System;

class Program {

	static void Main(string[] args)
	{
		int[] arr = {19, 0, 75, 52};

		try {

			// Try to generate an exception
			for (int i = 0; i < arr.Length + 1; i++) {
				Console.WriteLine(arr[i] / arr[i + 1]);
			}
		}

		// Catch block for invalid array access
		catch (IndexOutOfRangeException e) {

			Console.WriteLine("An Exception has occurred : {0}", e.Message);
		}

		// Catch block for attempt to divide by zero
		catch (DivideByZeroException e) {

			Console.WriteLine("An Exception has occurred : {0}", e.Message);
		}

		// Catch block for value being out of range
		catch (ArgumentOutOfRangeException e) {

			Console.WriteLine("An Exception has occurred : {0}", e.Message);
		}

		// Finally block
		// Will execute irrespective of the above catch blocks
		finally {
			for (int i = 0; i < arr.Length; i++) {
				Console.Write(" {0}", arr[i]);
			}
		}
	}
}
j