Denis
Denis

Reputation: 12087

How to catch TypeInitializationException?

How can I catch this TypeInitializationException? 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.

Upvotes: 1

Views: 1957

Answers (2)

Daniel Knoodle
Daniel Knoodle

Reputation: 384

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.

Upvotes: 1

Thomas Levesque
Thomas Levesque

Reputation: 292615

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)

Upvotes: 0

Related Questions