Try/Catch and threading

前端 未结 5 943
谎友^
谎友^ 2021-02-07 13:29

I have an idea why but I\'d like to ask if someone has a good grasp on why the exception raised inside a thread is never caught by the code that started it. Here\'s some very si

5条回答
  •  误落风尘
    2021-02-07 14:05

    Well in general, you've no idea where the originating thread will be by the time the exception is thrown in the new thread - why would it be waiting around for the thread to throw an exception?

    Think of the stacks involved - when an exception is thrown, it goes up the stack until it reaches an appropriate catch block. The new thread has a completely separate stack to the creating thread, so it'll never reach the catch block in the creating thread's stack.

    EDIT: Of course, you could design your system so that the creating thread did wait for other things to happen - a bit like the message loop in a Windows Forms application. The new thread could then catch the exception and send a message to the creating thread, which could then deal with the exception. That isn't the normal setup though - you have to do it all explicitly.

提交回复
热议问题