第七章 结构化异常处理 读书笔记

7.1 基本知识:

结构化异常处理:是一种操作系统提供的机制,用来优化程序的结构,提供更加健壮的程序执行环境。

异常:是指程序执行时遇到的任何错误情况或意外行为。

7.1.1

抛出异常:可能导致异常的代码段。

捕获异常:执行过程发生异常的代码段。

抛出和捕获异常是有try/catch/finally语句块处理的,是处理异常的主要机制。

try:指明执行过程需要监视抛出异常的代码块。

catch:指明在执行try语句后应该执行的代码块,用于处理或记录错误。

finally:包含代码清理资源或执行要在try块或catch块末尾执行的其他操作。无论是否发生异常都会执行,如不需要清理代码,可不   包含此块。

 基本语法:

try
            {
                //可能产生异常的代码块
            }
            catch (Exception)
            {
                //异常进行处理的代码块
              
            }

            finally
            {
                //最终执行的代码块
            }

例子:7.1抛出和捕获一个异常

 

View Code
using System;
using System.Collections.Generic;
using System.Text;

namespace e2
{
    class Program
    {
        static void Main(string[] args)
        {
            int a = 0, b = 10, c = 0;
            try
            {
                a = b / c;
            }
            catch (Exception e)
            {

                Console.WriteLine("发生异常:{0}", e.Message);
            }
            finally
            {
                Console.ReadLine();
            }

        }
    }
}

 

 运行结果:

 

例子7.2使用catch块捕捉多个异常

 

View Code
using System;
using System.Collections.Generic;
using System.Text;

namespace e3
{
    class myclass
    {
        static void ProcessString(string str)
        {
            if (str == null)
            {
                throw new ArgumentNullException();
            }
        }

        static void Main()
        {
            Console.WriteLine("输出结果为:");
            try
            {
                string str = null;
                ProcessString(str);
            }
            catch (ArgumentNullException e)
            {
                Console.WriteLine("第一个异常:{0}", e.Message);
            }
            catch (Exception e)
            {
                Console.WriteLine("第二个异常:{0}", e.Message);
            }

            finally
            {
                Console.ReadLine();
            }
        }
    }

}

运行结果:

try语句允许嵌套,语法如下


            try
            {
                //代码1
                try
                {
                    //代码2
                }
                catch (Exception)
                {

                    //代码3
                }

                finally
                {
                    //最终代码
                }

            }
            catch (Exception)
            {
               
                //处理异常代码
            }

            finally
            {
                //最终代码
            }

 

例子7.3 捕获特定异常(放在常规异常前)

 

View Code
    class MyClass
    {
        public void test(string s)
        {
            if (s == null)
                throw (new ArgumentNullException());
        }


        public static void Main()
        {
            MyClass x = new MyClass();
            try
            {
                string s = null;
                x.test(s);
            }
            catch (ArgumentNullException e)
            {
                Console.WriteLine("{0}First exception caught", e);
            }
            catch (Exception e)
            {
                Console.WriteLine("{0}Exccption caught", e);
            }
            finally
            {
                Console.ReadLine();
 
            }

        }
    }
    

运行结果:

 

7.4 System.Exception类是其他异常类的基类,发生错误是由程序运行环境抛出 System.Exception类适当的派生类。

     ApplicationException类由用户程序抛出,自定义异常类是ApplicationException类的派生类。

 

例子7.4:Exception类成员的使用

 

View Code
 class exception
    {
        static void Main()
        {
            try
            {
                Exception myEx = new Exception("原始异常");
                throw myEx;
            }
            catch (Exception ex)
            {
                Console.WriteLine("异常类型:{0}", ex.GetType().ToString());
                Console.WriteLine("异常信息:{0}", ex.Message);
                Console.WriteLine("堆栈跟踪;{0}", ex.StackTrace);
                Console.WriteLine("应用程序名称:{0}", ex.Source);
            }

            finally
            {
                Console.ReadLine();
            }
        }
        
    }

运行结果:

 

例子 7.5抛出预定义异常示例

 

View Code
    public class Person
    {
        public Person(){ }
        private int age;
        public int Value;
        public int Age
        {
            set 
            {
                if (Value > 10)
                    age = Value;
                else
                    throw new ArgumentException("发生异常,年龄小于10");
            }

            get 
            {
                Age = age;
                return Age;
            }
 
        }

    }

    class class1
    {
        static void Main()
        {
            Person p = new Person();
            try
            {
                p.Age = 9;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            finally
            {
                Console.ReadLine();
            }
        }

    }

运行结果:

 

 例子 7.6 自定义异常类:CustomException

 

View Code
    class numException : ApplicationException
    {
        public void printError()
        {
            Console.WriteLine("输入的数小于1或者大于9,请重新输入!!");
        }
    }

    class CustomException
    {
        static void Main()
        {
            string num;
            do
            {
                Console.WriteLine("请输入一个数字,输入'exit'退出程序!");
                num=Console.ReadLine();
                System.Text.RegularExpressions.Regex rx = new System.Text.RegularExpressions.Regex(@"^[1-9]$");//使用正则表达式判断
                try
                {
                    if(rx.IsMatch(num))
                    {
                       for(int i=0;i<10;i++)
                       {
                            Console.WriteLine("{0}*{1}={2}",i,num,i*Convert.ToInt32(num));
                       }
                    }
                    else
                    {
                        throw new numException();//必须人为抛出
                    }
                }
                catch(numException ex)
                {
                    ex.printError();
                    Console.WriteLine("异常类型:{0}",ex.GetType().ToString());//继承Exception
                }
            }
            while(!num.ToLower().Equals("exit"));
        }
    }

运行结果:

 

 例子 7.7 finally 发生异常时执行所有的清理工作

     finally块必须和try/catch一起使用,不管是否发生异常,finally都保证运行

 

 

  class Program
    {
        static void Main(string[] args)
        {
            int[] array1 ={ 00 };
            int[] arry2 ={ 00 };
            try
            {
                Array.Copy(array1, arry2, -1);
            }
            catch (ArgumentOutOfRangeException e)
            {
                Console.WriteLine("Error:{0}", e);
            }
            finally
            {
                Console.WriteLine("总是执行Finally块。");
            }
            Console.ReadLine();
        }
    }

运行结果:

 

posted @ 2012-02-07 13:04  ComBat  阅读(241)  评论(0编辑  收藏  举报