我有一个VB.NET类Flasher
,该类用于通过.Flash()
方法刷新带有某些固件的设备。但是,在刷新过程中可能会发生错误,在这种情况下将触发事件。我无法弄清楚如何处理此事件并在.Flash()
的调用堆栈中引发异常。
Class Flasher
Private myDevice As New FlashLib.Device
Public Function Flash() As String
AddHandler myDevice.ErrorEvent, AddressOf OnError
'... Do flashing stuff here that might send our `ErrorEvent` ...'
myDevice.flash_firmware("myfirmware.fw")
myDevice.restart()
Threading.Thread.Sleep(5000)
return "OK"
End Function
Public Sub OnError(ByRef Err As ErrEventArgs)
errMsg = String.Format(
"Device threw an error during flashing process. Type: {0}",
Err.error)
Throw New System.Exception(errMsg)
End Sub
Flasher
类依赖于C#库FlashLib
,它是ErrorEvent
的发起者:
namespace FlashLib
{
public delegate void ErrorEventHandler(ErrEventArgs err);
public interface Device
{
event ErrorEventHandler ErrorEvent;
}
}
问题是当我实例化Flasher
并调用.Flash()
时,想法是如果发生错误事件,.Flash()
的调用者将被引发异常,但是在.Flash()
执行的中间部分会跳出该函数并进入OnError()
。我的catch
子句不会在这里引发异常:
Dim flasher As New Flasher
Try
flasher.Flash()
Catch
Debug.Print("There was a problem with flashing")
End Try
相反,异常上升到顶部,并且显示错误消息框。然后从Flash()
方法中中断的地方继续执行 并继续进行。似乎VB.NET中的事件的行为就像软件中断一样:跳出您在处理程序中所做的任何操作,然后恢复之前的状态?我需要Flash()
的调用方才能在触发ErrorEvent
时捕获异常。
答案 0 :(得分:1)
不是让您的OnError
方法引发异常,而是让它设置一个可以在Flash
中进行测试的标志,然后在发现异常的情况下引发该异常。例如
Class Flasher
Private myDevice As New FlashLib.Device
Private errMsg As String
Public Function Flash() As String
AddHandler myDevice.ErrorEvent, AddressOf OnError
'... Do flashing stuff here that might send our `ErrorEvent` ...'
If errMsg IsNot Nothing Then
Throw New System.Exception(errMsg)
End If
myDevice.flash_firmware("myfirmware.fw")
myDevice.restart()
Threading.Thread.Sleep(5000)
return "OK"
End Function
Public Sub OnError(ByRef Err As ErrEventArgs)
errMsg = String.Format(
"Device threw an error during flashing process. Type: {0}",
Err.error)
End Sub