Error Handling

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
// this program is for error handling.

 

namespace throwException
{
    class Program
    {
        static string[] errorList = {"none", "simple", "index", "nested"}; // define error strings
        static void throwException(string arg) // define throwException function
        {
            switch (arg) // respond to different error type
            {
                case "none":
                    Console.WriteLine("No error found in this case");
                    break;
                case "simple":
                    Console.WriteLine("Simple error found in this case");
                    throw(new System.Exception()); //generate a general system exception
                case "index":
                    Console.WriteLine("Index error found in this case");
                    errorList[5] = "error"; //generate an "out of boudary" exception
                    break;
                case "nested": // a nested error
                    try
                    {
                        Console.WriteLine("Nested error try block is reached");
                        throwException("index"); // another call of throwException function
                    }
                    catch
                    {
                        Console.WriteLine("Catch the index out of boudary error!");
                    }
                    finally
                    {
                        Console.WriteLine("The finally block of nested error is reached!");
                    }
                    break;

            }
        }
        static void Main(string[] args)
        {
            Console.WriteLine("Error Handling Begins Here");
            Console.WriteLine("++++++++++");
            foreach (string Error in errorList) //go over all the error type
            {
                try
                {
                    Console.WriteLine("try block is reached!" + " Now {0} is tested", Error);
                    throwException(Error);
                }
                catch (System.IndexOutOfRangeException e)
                {
                    Console.WriteLine("The error message is {0}!", e.Message); // pop up error message
                }
                catch
                {
                    Console.WriteLine("Error Found, Unknow Error Type!");//if not out of boundry error, write this statement to screen
                }
                finally
                {
                    Console.WriteLine("main() finally block is reached!");
                    Console.WriteLine("++++++++++++++++++"); //final part
                }
            }
            Console.ReadKey();
        }
    }
}

Leave a Reply

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