Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle exceptions raised in other threads when unit testing?

When testing with Visual Studio Team Test unhandled exceptions in tests are caught and reported in the results. So I was kind of surprised to see the test hosting process (VSTestHost.exe) crash and showing the system crash dialog.

Upon further investigation this crash was an unhandled exception raised in another thread (more directly, it was an async socket callback). And indeed something like this crashes the hosting process:

[TestMethod]
void Test()
{
    new Thread(() => { throw new Exception(); }).Start();
}

Any advices what I should do there?

  • Should I just live with it, saying any code distributed/checked-in should be tested at least once anyway, and so such things most likely will be caught?
  • Should I try to install a global exception handler and check its status in every tear-down method?
  • Or maybe there are already exists stuff helping with this?
like image 882
gix Avatar asked May 21 '09 00:05

gix


People also ask

How do you handle exceptions in threads?

Exception handling in Thread : By default run() method doesn't throw any exception, so all checked exceptions inside the run method has to be caught and handled there only and for runtime exceptions we can use UncaughtExceptionHandler.

How do you test an exception in unit testing?

assertRaises(exception, callable, *args, **kwds) To catch any of a group of exceptions, a tuple containing the exception classes may be passed as exception. In the example below, a test function is defined to check whether ZeroDivisionError is raised.

How can you catch an exception thrown by another thread in Java?

There does not exist a way in Java to use try/catch around your start() method to catch the exceptions thrown from a secondary thread and remain multithreaded.


2 Answers

You can use a Global Exception handler to catch all of the uncaught exception in the AppDomain:

AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.UnhandledException += new EventHandler(UnhandledExceptionHandler);

I think it would work for exceptions thrown from other threads as well

like image 172
Dror Helper Avatar answered Oct 13 '22 18:10

Dror Helper


You could try setting AppDomain.CurrentDomain.UnhandledException and see if that works? I don't know how that interacts with the VS test harness thought

like image 26
Orion Edwards Avatar answered Oct 13 '22 19:10

Orion Edwards