且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C#拾遗系列(8):异常

更新时间:2022-09-02 15:17:22

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

 

namespace NetTest

{

    public class TestException

    {

        public void TestThrow()

        {

            //try 块必须与 catch 或 finally 块一起使用,并且可以包括多个 catch 块

            try

            {

                CustomException ex = new CustomException("test custom exception");

                ex.ModuleName = "Front-End";

                throw ex;

            }

            /*

            多个 catch 块可以串联在一起。多个 catch 块的计算顺序是从顶部到底部

            但是,对于所引发的每个异常,都只执行一个 catch 块。

            与所引发异常的准确类型或其基类最为匹配的第一个 catch 块将被执行。

            如果没有任何 catch 块指定匹配的异常筛选器,则将执行不带筛选器的 catch 块(如果有的话)。

            需要将带有最具体的(即派生程度最高的)异常类的 catch 块放在最前面

           */

            catch (CustomException ex)

            {

                System.Console.Out.WriteLine(ex.Message + "Module is:" + ex.ModuleName);

                System.Console.Out.WriteLine("------------------------------");

                System.Console.Out.WriteLine(ex.ToString());

            }

            catch (Exception ex)

            {

                System.Console.Out.WriteLine(ex.Message);

            }

 

            //Finally 块可让程序员清理中止的 try 块可能留下的任何不明确状态,

            //或释放任何外部资源(如图形句柄、数据库连接或文件流)

            //而不用等待运行库中的垃圾回收器来终结这些对象,finally块任何情况都执行

            finally

            {

                // Code to execute after try (and possibly catch) here

                System.Console.Out.WriteLine("test complete");

            }

        }

    }

 

    //自定义的异常

    [Serializable]

    class CustomException : Exception

    {

 

        public CustomException(string message):base(message)

        {           

        }

        public string ModuleName { getset; }

 

        public override string ToString()

        {

            return base.ToString() + this.ModuleName.ToString();

        }

    }

}

本文转自敏捷的水博客园博客,原文链接http://www.cnblogs.com/cnblogsfans/archive/2008/06/19/1225260.html如需转载请自行联系原作者


王德水