`
wangdeshui
  • 浏览: 247214 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

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

阅读更多

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 { get; set; }

 

        public override string ToString()

        {

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

        }

    }

}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics