C#中有關異常的捕獲演示

iamzxf發表於2015-03-16

C#中有關異常捕獲的演示:

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

namespace stringDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            int month;
            Console.WriteLine("input the month:");
            month = int.Parse(Console.ReadLine());

            try
            {
                switch (month)
                {
                    case 1: Console.WriteLine(31); break;
                    case 2: Console.WriteLine(28); break;
                    default: throw new ArgumentOutOfRangeException();
                }
            }
            catch (ArgumentOutOfRangeException e)
            {
                Console.WriteLine(e.Message);
            }
            finally {
                Console.ReadLine();
            }


        }
    }
}

用於陣列越界的演示:

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

namespace stringDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            int [] arr=new int[4];
            for (int i = 0; i < 4; i++)
                arr[i] = i;

            try { 
                for(int i=0;i<10;i++)
                {
                    Console.WriteLine(i);
                    if(i>=4)
                        throw new DivideByZeroException();
                }
            }
            catch (DivideByZeroException e) 
            { 
                Console.WriteLine(e.Message); 
            }
            finally{
                Console.ReadLine();
            }


        }
    }
}







相關文章