try catch 学习记入

执行过程

public void method(Action action)
{
    //2.method执行中
    try
    {
        action(); //3.调用委托
        string x = "5"; //如果action执行时出现了error,但是内部有catch机制并且没有继续throw出来,那么这里"会"执行
    }
    catch (Exception ex)
    {
        //8.捕获error
        string x = ex.Message; //如果action执行时出现了error,但是内部有catch机制并且没有继续throw出来,那么这里"不会"执行
    }
}
protected void Page_Load(object sender, EventArgs e)
{
    try
    {
        //1.调用method函数,并且传入委托
        method(delegate()
        {
            //4.执行委托函数
            try
            {
                throw new Exception("x"); //5.error 出现 
            }
            catch (Exception ex)
            {
                string x = ex.Message; //6.捕获error 
                throw ex; //7.把error传递下去 (如果没有把error传递,那么外部的catch就不会触发了)
            }
        });
        string xyx = "z"; //9.因为method函数中的catch没有在throw所以会执行这里
    }
    catch (Exception ex)
    {
        string x = ex.Message;
    }
    finally
    { 
        //10 finally 一定会执行!
    }
}

重点 catch有没有继续throw, finally一定会执行

 

自定义catch 

只要一个类继承了System.Exception 它就可以作为一个catch , 可以被throw

一个try 可以有多个 catch(不同的Class处理)

简单的说 throw new someClass 就是丢一个对象,new someClass()可以像普通的实例化一样,写一些初始化等等。

catch 捕获到的就是这个对象,就是一般的对象咯,一样可以调用属性或者方法等等。

public class MyEx : System.Exception
{       
    public MyEx() : base() { }      
    public MyEx(string message, Exception innerException) : base(message, innerException) { }
    public MyEx(Int64 number) //初始化
    {
        this.number = number;
    }
    public Int64 number { get; set; }
}
  
protected void Page_Load(object sender, EventArgs e)
{
    try
    {
        throw new MyEx(5);
    }
    catch (MyEx ex)
    {
        Int64 z = ex.number; //调用公有属性
    }
    catch (Exception ex)
    {
        string x = ex.Message;
    }
    finally
    { 
        //10 finally 一定会执行!
    }
}

 

posted @ 2014-09-24 10:56  兴杰  阅读(318)  评论(0编辑  收藏  举报