0

I'm implementing something similar to Handling unhandled exceptions problem :

        Application.ThreadException +=
            (s, eargs) => LogException(eargs.Exception);
        AppDomain.CurrentDomain.UnhandledException +=
            (s, eargs) =>
                LogException((Exception)eargs.ExceptionObject);
        Application.SetUnhandledExceptionMode(
            UnhandledExceptionMode.CatchException);

This has been working well in all of my applications until now. When I encounter an error in this asynchronous handler:

    void DnsResolveCallback(IAsyncResult result)
    {
        try
        {
            IPHostEntry entry = Dns.EndGetHostEntry(result);
            IPEndPoint endpoint = new IPEndPoint(entry.AddressList[0], Port);
            socket = new Socket(endpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            socket.BeginConnect(endpoint, ConnectCallback, null);
        }
        catch (Exception)
        {
            SetStatus(ConnectStatus.Disconnected);
            throw;
        }
        SetStatus(ConnectStatus.Connecting);
    }

I am able to catch it if I add

        AppDomain.CurrentDomain.FirstChanceException +=
            (sender, eargs) => LogException(eargs.Exception);

but not otherwise. I don't want to have to use FirstChanceException because that seems to be nasty and defeat the whole purpose of exception handling.

Community
  • 1
  • 1
Reinderien
  • 8,154
  • 3
  • 41
  • 70
  • Which statement in `DnsResolveCallback` is throwing the exception? – phoog Apr 05 '11 at 21:24
  • Depending on the problem, the EndGetHostEntry (if the host wasn't resolved) or sometimes entry.AddressList[0] because it can be empty. However, which line throws isn't really the problem here; anything thrown in this function produces the same results. – Reinderien Apr 05 '11 at 21:41
  • Ok, I'm just wondering whether the exception is being handled somewhere else so it's not actually "unhandled". – phoog Apr 05 '11 at 21:56
  • Nah, it's falling through and causing the application to close. – Reinderien Apr 05 '11 at 22:01
  • The code doesn't make a lot of sense, it *always* terminates the app. The callback runs on a tp thread. You might as well call Environment.Exit() right away. Not getting AppDomain.UnhandledException is novel, I'm not buying until I can try it. – Hans Passant Apr 05 '11 at 22:53

0 Answers0