我想抛出给定System.Exception
的{{1}},将Type
作为Type
的自变量传递,其中Sub
是{ {1}}。
然后我会这样称呼Throw
:Exception
到目前为止,我想到了这个,但是Sub
不高兴:
ExceptionType未定义
Call ThrowEvent("Wrong format: MyString must comply with the following pattern ***, System.FormatException)
我从来没有将DirectCast用于接口以外的任何事情(通常是在玩Collections时)
我找到了this,但并不太了解整个图片。
我找到了this,但我不知道我应该如何DirectCast
答案 0 :(得分:1)
正如已经讨论过的评论一样,这根本不是一个好主意。这个概念通常是错误的,并且exceptin仍然会弄乱您的代码。您应该使用常规处理方法进行“尝试/捕获”操作。
但是,如果您真的想将“ throw”包装为“ log and throw”,那么最简单的方法是:
Public Shared Sub ProcessThrow(Ex As Exception)
'Do your logging here
Throw Ex
End Sub
并称呼它
ProcessThrow(New FormatException("Wrong format: MyString must comply with the following pattern ***""))
更好的方法是
Public Shared Sub HandleEx(Ex As Exception)
'Do your logging here
End Sub
并这样称呼它
Try
'Do something
Throw New FormatException("Wrong format: MyString must comply with the following pattern ***")
Catch ex As Exception
HandleEx(ex)
'Recover
End Try
答案 1 :(得分:0)
我理解不推荐这样做,并且我将不会实施此解决方案,但是为了完整起见并帮助理解泛型函数的工作原理,以下是两种解决方案:
Public Shared Sub ThrowEvent(Of TException As {System.Exception, New})()
Throw New TException() 'Passing arguments to the creator is not permited
End Sub
Public Shared Sub ThrowEvent(Of TException As {System.Exception})(ByVal MyMessage As String)
Dim MyException As TException = Activator.CreateInstance(GetType(TException), New Object() {MyMessage})
Throw MyException
End Sub
同样,这回答了问题,但是问题是寻求不推荐的策略。