开发者

How to catch TypeInitializationException?

开发者 https://www.devze.com 2023-02-10 22:35 出处:网络
How can I catch this TypeInitializationException?开发者_如何学JAVA Don\'t really care if it is C# or VB.NET code. Here is some sample code of what I am trying to figure out (this is not real code - ju

How can I catch this TypeInitializationException?开发者_如何学JAVA Don't really care if it is C# or VB.NET code. Here is some sample code of what I am trying to figure out (this is not real code - just something to show what I am dealing with):

Public Class Test 
    Public Shared testObj as Object = CreateObj()

    Public Shared Function CreateObj() as Object
         throw new Exception("Ha!")
    End Function

    Public Shared Sub Main()
       Dim i as Integer = 0
    End Sub
End Class

Suppose I have no control over CreateObj method.


In VB you have a couple of options depending on what type of application it is.

If the Application is a console app or windows form app then you can extend the My class with an UnhandledException event.

Namespace My
    Partial Friend Class MyApplication
        Private Sub MyApplication_UnhandledException(ByVal sender As Object, ByVal e As Microsoft.VisualBasic.ApplicationServices.UnhandledExceptionEventArgs) Handles Me.UnhandledException
           'Handle error here
        End Sub
    End Class
End Namespace

If it's an ASP.Net web app then add some code to the Global.asax file (events below truncated for brevity).

Public Class Global_asax
    Inherits System.Web.HttpApplication

    Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
        ' Fires when an error occurs
    End Sub

    Private Sub Global_asax_Error(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Error
        'Catches all errors
    End Sub
End Class

As a rule you shouldn't call a method from a type initializer. Use the class initializer to set the initial value in your Sub Main.


Just use a Try/Catch block, as for any other exception... If Main is the program entry point, you're out of luck, because the exception might be thrown before you have a chance to catch it. I say "might" because I'm not sure about the rules regarding type initialization in VB; if they're the same as in C# 4, the code you posted will run fine, because the type initializer won't be executed until it's actually necessary, and in your code it's never necessary (because testObj is never used)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号