Exception Handling Programming Examples in C#

In this Section you will learn:
Some programming examples of exception handling with definition. It will help you to understand error control techniques very clearly.
1. Write a program to handle NullReferenceException and fix the error message "Object reference not set to an instance of an object."
Answer
This exception occurs when there is reference to an object but object is empty or null. See the example, it throws NullReferenceException.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Null_Reference_Exception
{
    class Program
    {
        static void Main(string[] args)
        {
            string text = null;
            int length = text.Length;
            Console.WriteLine(length);
            Console.ReadLine();
        }
    }
}

In this example the string variable is null so, text.Length properties cant calculate the lenght of string and return NullReferenceException. To handle this problem, use NullReferenceException handler in catch block.

 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Null_Reference_Exception
{
    class Program
    {
        static void Main(string[] args)
        {
            string text = null;
            try
            {
                int length = text.Length;
                Console.WriteLine(length);
                Console.ReadLine();
            }
            catch (NullReferenceException nex)
            {
                Console.WriteLine(nex.Message);
            }
            Console.ReadLine();
        }
    }
}

Output

Now your program will execute and doesn't break with exception.
Object reference not set to an instance of an object.
__

Summary

In the next chapter you will get some programming exercises. It is Do it Yourself section and you must try to solve programming problems using your skills. In the next chapter some programming exercises are ready for you.

 

Share your thought