2
method A()
{
  try
  {
    Thread t = new Thread(new ThreadStart(B));
    t.Start();
  }
  catch(exception e)
  {
    //show message of exception
  }      

}

method B()
{
 // getDBQuery
}

a exception in B but not catched. does it legal in .net?

Zong
  • 6,160
  • 5
  • 32
  • 46
SleeplessKnight
  • 2,125
  • 4
  • 20
  • 28
  • See answer to [this question](http://stackoverflow.com/q/5983779/395718) for ways to get exception from another thread. – Dialecticus Nov 04 '13 at 15:34

2 Answers2

7

Correct, exceptions from a Thread are not forwarded to the caller, the Thread should handle this by itself.

The most general answer is that you should not be using a (bare) Thread here. It's not efficient and not convenient.

When you use a Task, the exception is stored and raised when you cal Wait() or Result.

H H
  • 263,252
  • 30
  • 330
  • 514
4

When A is finished executing B might still be running as it is on an independent thread. For that reason it is impossible by principle for A to catch all exceptions that B produces.

Move the try-catch to inside of B. The Thread class does not forward exceptions.

Better yet, use Task which allows you to propagate and inspect exceptions.

usr
  • 168,620
  • 35
  • 240
  • 369