consol app global exception handling

K

Karl Seguin

I'm trying to setup a global exception handler by attaching a handler to the
CurrentDomain.UnhandledException exception.

Here's sample code I got from the net:

Module Module1

Sub Main()
Dim currentDomain As AppDomain = AppDomain.CurrentDomain
AddHandler currentDomain.UnhandledException, AddressOf MyHandler

Dim s As String
Console.WriteLine(s.ToString())
End Sub

Sub MyHandler(ByVal sender As Object, ByVal args As
UnhandledExceptionEventArgs)
Dim e As Exception = DirectCast(args.ExceptionObject, Exception)
Console.WriteLine("MyHandler caught : " + e.Message)
End Sub

End Module

However, when the code is run, I still get an "Unhandled Exception" error
because of the null reference...any help?

Karl
 
V

Vladimir Sadov [MSFT]

Adding a handler for UnhandledException is a way to get notified about
UnhandledException. This does not change the fact that the exception is
unhandled. To handle all exceptions that can be handled you need to put
your code in a Try Catch block like this:

Module Module1

Sub Main()
Try
Dim currentDomain As AppDomain = AppDomain.CurrentDomain
AddHandler currentDomain.UnhandledException, AddressOf MyHandler


Dim s As String
Console.WriteLine(s.ToString())
Catch e As Exception
Console.WriteLine("Catch caught : " + e.Message)
End Try
End Sub

Sub MyHandler(ByVal sender As Object, ByVal args As
UnhandledExceptionEventArgs)
Dim e As Exception = DirectCast(args.ExceptionObject, Exception)
Console.WriteLine("MyHandler caught : " + e.Message)
End Sub

End Module

Vladimir [VB.Net team]

This posting is provided "AS IS" with no warranties, and confers no rights.
Use of included script samples are subject to the terms specified at
http://www.microsoft.com/info/cpyright.htm

Note: For the benefit of the community-at-large, all responses to this
message are best directed to the newsgroup/thread from which they
originated.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top