Exception Handling Programming Exercises C#

In this Section you will learn:
  • How to solve problems if exception generates?
  • Solve practice question
Qu 1. This program is throwing exception IndexOutOfRangeException. Using your skills fix this problem using try catch block.
Answer
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Null_Reference_Exception
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] list = new string[5];
            list[0] = "Sunday";
            list[1] = "Monday";
            list[2] = "Tuesday";
            list[3] = "Wednesday";
            list[4] = "Thursday";

            for (int i = 0; i <= 5; i++)
            {
                Console.WriteLine(list[i].ToString());
            }
            Console.ReadLine();

        }
    }
}

 
Qu 2. The given program is throwing OverflowException. Fix it.
Answer
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Overflow_Exception
{
    class Program
    {
        static void Main(string[] args)
        {
            int num1, num2;
            byte result;

            num1 = 30;
            num2 = 60;
            result = Convert.ToByte(num1 * num2);
            Console.WriteLine("{0} x {1} = {2}", num1, num2, result);
            Console.ReadLine();
        }
    }
}

Summary

In this chapter you have did some exception handling exercises. In the next chapter we will learn constructors and Destructors in C#.

 

Share your thought