Per method exception and ensure handlers
April 17th, 2006
In Ruby, methods automatically define begin/end blocks. That makes it easy to write exception handlers and ensure blocks:
1 2 3 4 5 6 7 8 9 10 11 |
def access!(options={}) raise AuthorizationFailure if self.email != options[:email] self.download_count += 1 rescue AuthorizationFailure self.unauthorized_access_count += 1 raise ensure self.save! end |
It is important to re-raise the exception in the exception handler, or else the exception will be silently thrown away.