七、 定制异常-DatabaseUnavailableException
第二个定制异常类是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属性。 Inherits DatabaseException
Public Sub New(ByVal ex As Exception)
MyBase.New("The database is not available.", ex)
End Sub
End Class
八、 Customer类
Customer类是一个简单类,这个类的构造器使用一个数据库名和一个CustomerID作为参数并且负责检索该顾客相应的数据。该构造器要做的第一件事情是,通过使用ConnectDB方法尝试建立到数据库的连接。具体代码如下:
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属性包装了原始的异常。 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
如果你成功地连接到数据库,那么你就试图使用GetCustomer方法来检索相应于指定CustomerID的数据,详见下面的代码:
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属性。 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
九、 总结
定制异常类型是VB.net语言中的一个非常有力的特征。.NET框架提供了许多标准的异常类型,对于大多数应用而言,已经足够了。事实上,你可能会很少用到标准异常之外的东西;但是,特殊情况下定制自己的异常会提高你的应用程序的健壮性。
