Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
138 views
in Technique[技术] by (71.8m points)

c# - Exception handling in threads

Recently i have attended an interview . A code snippet is given to me.I know,the interviewer took it from albhari's threading sample.

public static void Main() 
{
    try 
    {
        new Thread (Go).Start();
    }
    catch (Exception ex)
    {
        // We'll never get here!
       Console.WriteLine ("Exception!");
    }
}

static void Go() { throw null; }

The modification of the above code as

public static void Main()
{
    new Thread (Go).Start();
}

static void Go() 
{
    try 
    {
        ...
        throw null; // this exception will get caught below
        ...
    }
    catch (Exception ex) 
    {
        Typically log the exception, and/or signal another thread
        that we've come unstuck
        ...
    }
}

would be the good candidate to handle the exception.

I have been asked, "Except the above trail what are the other alternatives would fit as good solution?. It was hard to find the alternative,so i raise it here to gather your suggestion.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Exception thrown in a thread normally couldn't be caught in another thread.

You'd better to catch it in function Go and pass it to main thread explicitly.

However, if you just want to log all unhandled messages from all threads, you may use AppDomain.UnhandledException event or equivalent events at Application class if you are developing WinForms or WPF app.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...