一个比较经典的C#异常处理程序实例

来源:互联网 发布:网络建设与管理很累吗 编辑:程序博客网 时间:2024/05/22 05:04
 

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


namespace CSharpPractice
{
    class Program
    {
        static void Main(string[] args)
        {
            Program test = new Program();

            ///①调用GenerateException
            try
            {
                test.GenerateException();
            }
            ///⑦Main函数中的异常链不空,捕获异常
            catch (Exception ex)
            {
                int i = 1;
                Console.WriteLine("\nMain函数现在所有的异常:");
                while (ex != null)
                {

                    Console.WriteLine("\t异常{0}:{1}", i++, ex.Message);
                    ///依次输出异常链上的异常
                    ex = ex.InnerException;
                }
            }
            ///⑧执行finally
            finally
            {
                Console.WriteLine("main函数结束!");
            }
            Console.ReadKey();
        }
        void GenerateException()
        {
            ///②执行GenerateException
            Console.WriteLine("调用GenerateException");
            int mySize = 3;
            byte[] Mystream = new byte[mySize];
            int iterations = 5;
            ///③数组发生越界
            try
            {
                for (byte b = 0; b < iterations; b++)
                {
                    Mystream[b] = b;
                }
            }
            ///④定义了多个catch块,只执行最合适的
            catch (IndexOutOfRangeException iore)
            {
                Console.WriteLine("catch越界异常:{0}", iore.Message);
                ///⑤抛出一个异常,第二个参数为此异常的InnerException
                throw new Exception("我抛出的异常", iore);
            }

            catch (Exception ex)
            {
                Console.WriteLine("GenerateException中捕获普通异常:{0}", ex.Message);
            }
            ///⑥执行finally
            finally
            {
                Console.WriteLine("GenerateException结束");
            }
            //Console.ReadKey();
        }
    }
}