在VB 2005中定制自己的异常
定制异常:CustomerNotFoundException
第一个定制异常类是CustomerNotFoundException。当你试图在你的数据库中查找一个客户但未找到相应的匹配时你会抛出这个异常。实现代码如下所示:
Public Class CustomerNotFoundException Inherits DatabaseException Private m_CustomerID As Long Public ReadOnly Property CustomerID() As Long Get Return m_CustomerID End Get End Property Public Sub New(ByVal customerID As Long) MyBase.New("Customer ID was not found.") m_CustomerID = customerID End Sub End Class
这个类继承自你前面所创建的DatabaseException基类。它仅包含一个构造器--其参数为customerID。当调用这个构造器时,你把文本串"Customer ID was not found."传递到基类的构造器以用作Message属性。你还有一个已定义的只读属性CustomerID。你将使用这个CustomerID属性来存储要被作为一个参数传递的CustomerID的值。它是一个只读属性,因为把这个值改变为除了引发异常的值以外的值并没有什么意义。
定制异常:DatabaseUnavailableException
Public Class DatabaseUnavailableException Inherits DatabaseException Public Sub New(ByVal ex As Exception) MyBase.New("The database is not available.",ex) End Sub End Class
这个类非常相似于你的CustomerNotFoundException类。你不用为这个类定义任何其它属性,但是它们的主要区别在于,它把一个System.Exception作为一个参数并且把它传递到你的基类的构造器中。这个System.Exception参数将成为你的DatabaseUnavailableException的InnerException属性。
Customer类
Private Sub ConnectDB(ByVal database As String, _ ByRef cn As OleDbConnection) cn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0; _ Data Source=" & _ """" & database & """" Try cn.Open() Catch ex As Exception Throw New DatabaseUnavailableException(ex) End Try End Sub
你试图在一个Try语句内打开数据库连接。如果抛出任何异常的话,你就会捕获它并抛出一个DatabaseUnavailableException-这个异常用它的InnerException属性包装了原始的异常。
Private Sub GetCustomerData(ByVal cn As OleDbConnection, _ ByVal customerID As Long) Dim cmd As New OleDbCommand Dim reader As OleDbDataReader cmd.Connection = cn cmd.CommandText = "SELECT * FROM CUSTOMER WHERE ID = " _ & customerID reader = cmd.ExecuteReader If reader.HasRows Then reader.Read() m_id = reader.Item("ID") m_firstname = reader.Item("Firstname") m_lastName = reader.Item("Lastname") m_street = reader.Item("Street") m_city = reader.Item("City") m_state = reader.Item("State") m_zipCode = reader.Item("Zip") Else Throw New CustomerNotFoundException(customerID) End If End Sub
上面的代码中,你执行了一个SQL查询--其中使用CustomerID来指定你想要检索哪个顾客的数据。如果查询返回一个结果,那么你使用从该查询返回的值设置Customer类的属性。但是,如果你没有得到任何值的话,你将使用customerID作为构造器的参数抛出一个CustomerNotFoundException异常。这个值将用于设置你的CustomerNotFoundException对象的CustomerID属性。
总结
0
相关文章