给定类似的代码:
Try
Try
'Code that throws an OleDBException
Catch dbEx as System.Data.OleDb.OleDbException
Console.WriteLine("Inner Specific Exception handler.")
Dim newEx As New System.Exception("Database Error Handled.", dbEx)
Throw newEx
Catch ex as Exception
Console.WriteLine("Inner Generic Exception handler.")
End Try
Catch ex as Exception
Console.WriteLine("Outer Generic Exception handler.")
End Try
这段代码已经精简了很多,实际实现对OleDBException
做了更多的处理,然后丢失了堆栈跟踪,但我的问题是,当抛出OleDbException
时,会向控制台写入什么?
我希望看到:
Inner Specific Exception handler.
Inner Generic Exception handler.
但我认为它实际上会输出:
Inner Specific Exception handler.
Outer Generic Exception handler.
或者有人知道一种可靠的方法可以让OleDbException
持续投掷,这样我就可以自己测试了吗?
你不能轻易抛出OleDBException,因为它说不能访问友元构造函数,但为什么不用一种更简单的异常类型来测试它呢?异常类型对您的测试没有影响。
Try
Try
Throw New ArgumentException("Throwing up!")
'Code that throws an OleDBException
Catch dbEx As ArgumentException
Console.WriteLine("Inner Specific Exception handler.")
Dim newEx As New System.Exception("Database Error Handled.", dbEx)
Throw newEx
Catch ex As Exception
Console.WriteLine("Inner Generic Exception handler.")
End Try
Catch ex As Exception
Console.WriteLine("Outer Generic Exception handler.")
End Try
OleDbException类的构造函数似乎不是公共的,所以您可能无法简单地自己抛出一个。
不过,您可以通过OleDB连接执行查询来实现您的目标,您知道该连接将失败。例如:
SELECT NoColumn FROM NoTable
应该这样做,除非你运气不好,有一个名为"NoTable"的表,其中有一个列为"NoColumn"。:)