1

I am learning Ruby. I am trying to make a connection to MySQL db using mysql gem. One of my concern is connection closing.

How should I ensure the connection closing at unexpected situations such as exception throwing?

eonil
  • 83,476
  • 81
  • 317
  • 516
  • That's what `begin`/`rescue`/`ensure` (aka `try`/`catch`/`finally`) is for. –  Mar 04 '13 at 05:12

1 Answers1

1

You mean, something like this?

begin
  db = open_mysql_connection
  # do stuff
ensure
  # this block is always executed, even if exception is raised
  db.close
end
Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
  • BTW, the comment should read "this block is _almost_ always executed". If another thread sends a `raise` or `kill` once you've entered the ensure but before you execute db.close, the connection can leak. stdlib's [`Timeout::timeout`](http://www.ruby-doc.org/stdlib-1.9.3/libdoc/timeout/rdoc/Timeout.html#method-c-timeout) uses just such an inherently unsafe thread race to do its business. – dbenhur Mar 04 '13 at 05:56
  • @dbenhur: interesting, have to look into it. – Sergio Tulentsev Mar 04 '13 at 05:58
  • Charles Nutter describes in detail the inherent hinkiness of `Thread#raise` and friends: [Ruby's Thread#raise, Thread#kill, timeout.rb, and net/protocol.rb libraries are broken](http://blog.headius.com/2008/02/ruby-threadraise-threadkill-timeoutrb.html) – dbenhur Mar 04 '13 at 06:01