exceptions.md - brainchildservices/curriculum GitHub Wiki

Slide 1

C# - Exception

When executing C# code, different errors can occur: coding errors made by the programmer, errors due to wrong input, or other unforeseeable things.
When an error occurs, C# will normally stop and generate an error message. The technical term for this is: C# will throw an exception (throw an error).

Common Exception that we encounter:

  • IndexOutOfRangeException: This exception is thrown when you try to access an element from an array, list, or any indexable sequence using an invalid index value
  • NullReferenceException: This exception is thrown when you try to call a method/property/indexer/etc. on a variable that contains a null reference—that is, it doesn’t point to any object.
  • DivideByZeroException: This exception is thrown when you try to divide by zero

Slide 2

 using System;

 public class Program
 {
      public static void Main()
     {
	int[] arr = new int[2];
	arr[0] = 1;
	arr[1] = 1;
	//arr[2] = 1;     //IndexOutOfRangeException: Index was outside the bounds of the array.
	
	string name = null;
	//name.ToUpper();     //NullReferenceException: Object reference not set to an instance of an object.
	
	int k = 10;
	//Console.WriteLine(k/0);     //DivideByZeroException: Attempted to divide by zero.
 	}
 }