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

More Articles

 

Share your thought



PLEASE DISABLE ADBLOCKER AND SUPPORT US!

Please support us by enabling ads on this page. Refresh

YOU DON'T LIKE ADS, WE ALSO DON'T LIKE ADS!
 
But we have to show ads on our site to keep it free and updated. We have to pay huge server costs, domain costs, CDN Costs, Developer Costs, Electricity and Internet Bill. Your little contribution will encourage us to regularly update this site.