NullReferenceException Exception : Buildin Exceptions « Development Class « C# / C Sharp






NullReferenceException Exception

 
using System;
   
class MyClass {
    public int Value;
}
   
class MainClass
{
    public static void Main()
    {
        try
        {
            MyClass MyObject = new MyClass();
            MyObject = null;
   
            MyObject.Value = 123;
   
            // wait for user to acknowledge the results
            Console.WriteLine("Hit Enter to terminate...");
            Console.Read();
        }
        catch(NullReferenceException)
        {
            Console.WriteLine("Cannot reference a null object.");
   
            // wait for user to acknowledge the results
            Console.Read();
        }
    }
}

           
         
  








Related examples in the same category

1.Throw and Catch an IO exception because the file zxcvb.data doesn't exist
2.OutOfMemoryException Exception
3.StackOverflowException Exception
4.InvalidCastException Exception
5.IndexOutOfRangeException Exception
6.OverflowException Exception
7.Throw Index Out Of Range Exception
8.Throw Null reference Exception
9.Throw Invalid Operation Exception
10.Argument Null Exception
11.Throw Argument Out Of Range Exception
12.ArgumentException is thrown when one of the arguments provided to a method is not valid.
13.OverflowException