002.C#中异常的抛出与捕获

来源:互联网 发布:局域网禁止上网软件 编辑:程序博客网 时间:2024/06/07 02:04

在线演示:http://v.youku.com/v_show/id_XMzQxNTk1NDg0.html
演示下载:http://115.com/file/dp5iilzi

说明:建议下载演示视频后观看,在线演示不是很清晰。另外,演示下载中包含有源代码。

一、异常的抛出
虽然过多的使用异常会造成程序性能的降低,但是,该使用异常的时候,也不能吝啬而不使用。
否则,反而带来不少的麻烦。
比如,再对传递给函数的各个参数值进行检测的时候,遇到不符合条件的参数,可能就需要抛出异常了。
如下面的代码所示:
当检测到参数CustomerID为空的时候,就会抛出一个ArgumentException的异常。

/// <summary>/// 获取指定编码的客户信息。/// <para>如果获取成功则返回包括指定客户信息的实体对象,否则返回null(表示系统中不存在指定编码的客户)。</para>/// 光脚丫思考 4:49 2011-12-06/// </summary>/// <param name="CustomerID">客户编码。</param>public static Customer RetrieveCustomer(string CustomerID){    // 1、确认各参数的有效性。    if (string.IsNullOrEmpty(CustomerID))        throw new ArgumentException("客户编码不能为空。", "CustomerID");    // 2、执行数据库查询操作,并返回结果。    string Sql = "SELECT * FROM dbo.Customers WHERE CustomerID = @CustomerID";    List<SqlParameter> Parameters = new List<SqlParameter>();    SqlParameter Parameter = new SqlParameter("@CustomerID", CustomerID);    Parameters.Add(Parameter);    DataSet ResultDataSet = SqlHelper.ExecuteDataSet(Sql, CommandType.Text, Parameters);    if (ResultDataSet.Tables.Count != 1)        throw new Exception("执行数据库查询时发生了异常,导致未能返回预期的结果。");    if (ResultDataSet.Tables[0].Rows.Count <= 0)        return null;    DataRow firstRow = ResultDataSet.Tables[0].Rows[0];    Customer CustomerObject = new Customer()    {        CustomerID = firstRow["CustomerID"].ToString(),        Address = firstRow["Address"].ToString(),        City = firstRow["City"].ToString(),        CompanyName = firstRow["CompanyName"].ToString(),        ContactName = firstRow["ContactName"].ToString(),        ContactTitle = firstRow["ContactTitle"].ToString(),        Country = firstRow["Country"].ToString(),        Fax = firstRow["Fax"].ToString(),        Phone = firstRow["Phone"].ToString(),        PostalCode = firstRow["PostalCode"].ToString(),        Region = firstRow["Region"].ToString()    };    return CustomerObject;}

诸如上例的参数有效性检测,可能更好的方式,就是抛出一个异常了。
基本上.NET本身也抛出了很多类似的异常。
在这种情况下,如果不使用抛出异常的方式,而是采用函数返回值的方式,
则可能导致函数揭露的检测结果信息过少,或者我们需要定义的返回信息过多。
总之,都是有些不尽如人意的地方。

二、异常的捕获
通常,我们需要在呈现层捕获异常,并对异常进行处理。
否则的话,异常可能直接就暴露给用户了,显然这是不对的。
下面的代码,演示了如何捕获并以友好的方式处理异常信息。

try{    // ***************************************************************    // 1、获取并显示指定编码的客户信息。    // ***************************************************************    string CustomerID = "ALFKI";    Customer CustomerObject = Customer.RetrieveCustomer(CustomerID);    if (CustomerObject == null)    {        this.MessageLabel.Text = string.Format("系统中不存在编码为[{0}]的客户。", CustomerID);        this.MessageLabel.ForeColor = Color.Red;        this.MessageLabel.Visible = true;        return;    }    this.CustomerIDTextBox.Text = CustomerObject.CustomerID;    this.CompanyNameTextBox.Text = CustomerObject.CompanyName;    this.ContactNameTextBox.Text = CustomerObject.ContactName;    this.ContactTitleTextBox.Text = CustomerObject.ContactTitle;    this.AddressTextBox.Text = CustomerObject.Address;    this.CityTextBox.Text = CustomerObject.City;    this.RegionTextBox.Text = CustomerObject.Region;    this.PostalCodeTextBox.Text = CustomerObject.PostalCode;    this.CountryTextBox.Text = CustomerObject.Country;    this.PhoneTextBox.Text = CustomerObject.Phone;    this.FaxTextBox.Text = CustomerObject.Fax;}catch (Exception ex){    this.MessageLabel.Text = ex.Message;    this.MessageLabel.ForeColor = Color.Red;    this.MessageLabel.Visible = true;    return;}


三、总结
能不用异常就不用,但是该用的时候也当勇敢地使用。^_^

光脚丫思考 19:19 2012-01-10