Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i get ruby to output an exception inside a thread?

When I spawn a thread with Thread.new{} it looks like any exception that happens in that thread never sees the light of day, and the app just quietly ignores it

like image 840
Tyler Gillies Avatar asked Aug 02 '10 19:08

Tyler Gillies


People also ask

Can thread throws an exception?

An AppDomainUnloadedException is thrown in a thread because the application domain in which the thread is executing is being unloaded. The common language runtime or a host process terminates the thread by throwing an internal exception.

What happens when an exception occurs in a thread?

If an unhandled exception occurs in the main thread of an application, the main thread terminates, along with your entire application. An unhandled exception in a spawned worker thread, however, will terminate only that thread.

Is multithreading possible in Ruby?

Ruby makes it easy to write multi-threaded programs with the Thread class. Ruby threads are a lightweight and efficient way to achieve concurrency in your code.


2 Answers

Normally, threads are isolated from each other, so exception in one won't terminate the whole application.

But, although I never used them, Thread class has several abort_on_exception methods, even with some examples. They should do what you want.
http://corelib.rubyonrails.org/classes/Thread.html

like image 77
Nikita Rybak Avatar answered Oct 20 '22 05:10

Nikita Rybak


Adding to Nikita's answer, you can also trigger the exception by calling thread.join on the thread you've generated.

If you run the program with the debug flag on (ruby -d), then you'll also abort when an unhandled exception is raised in a thread.

like image 35
Andrew Grimm Avatar answered Oct 20 '22 05:10

Andrew Grimm