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."

This exception occurs when there is reference to an object but object is empty or null. See the example, it throws NullReferenceException.

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.

  • Output

    Now your program will execute and doesn’t break with exception.

    Object reference not set to an instance of an object.



    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.

    Leave a Reply

    Your email address will not be published. Required fields are marked *