# Threads and exceptions

**URL:** <https://www.ruby-forum.com/t/threads-and-exceptions/54499>\
**Category:** Ruby\
**Created:** [March 7, 2006, 3:50am UTC](https://www.ruby-forum.com/t/threads-and-exceptions/54499 "2006-03-07T03:50:56Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![aseldo](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/e95f7d/32.png) [@aseldo](https://www.ruby-forum.com/u/aseldo)\
**Post date:** [March 7, 2006, 3:50am UTC](https://www.ruby-forum.com/t/threads-and-exceptions/54499/1 "2006-03-07T03:50:56Z")

</div>

I’ve built a small web service using webrick. The service runs on a  
separate  
thread. When it gets an exception it, apparently, dies…it being the  
thread.

Is there a way to catch the exception without the thread exiting? The  
code  
is opening a file so I wrapped it in a begin/rescue block, but it  
doesn’t  
seem to help.

```
begin
  File.open(buffer[:file_name], 'a') do |f|
    f.print(buffer[:text])
  end
rescue Exception
  @logger.error("could not write message\n #{$!}\n file

```

> #{buffer[:file\_name]}\<\n message \>#{buffer[:text]}\<")  
> end

If the file is invalid I think the thread dies – but I don’t see a  
message  
anywhere.

-Kelly

---

<div class="post-metadata">

**Author:** ![aseldo](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/e95f7d/32.png) [@aseldo](https://www.ruby-forum.com/u/aseldo)\
**Post date:** [March 7, 2006, 9:02am UTC](https://www.ruby-forum.com/t/threads-and-exceptions/54499/2 "2006-03-07T09:02:03Z")

</div>

2006/3/7, Kelly F. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid):

> ```
> f.print(buffer[:text])
> end
> rescue Exception
> @logger.error("could not write message\n #{$!}\n file
> 
> ```
> 
> > #{buffer[:file\_name]}\<\n message \>#{buffer[:text]}\<")  
> > end
> 
> If the file is invalid I think the thread dies – but I don’t see a message  
> anywhere.

For debugging purposes you can use Thread.abort\_on\_exception=true  
which will kill the interpreter with a stack dump. Normally your  
rescue clause should do the job - unless there is something outside  
the block that throws.

Kind regards

robert
