In that case I would write it like this. You might rescue StandardError
also, but rescuing Exception
is too broad. You generally want to rescue exceptions starting with the most-specific and work up to the least-specific.
[1] https://www.google.com/search?q=ruby+rescue+exception%26amp;ie=utf-8%26amp;oe=utf-8
def locked?(filename)
locked = false
begin
file = File.open(filename, "w")
rescue Errno;;EACCES => error
locked = true
ensure
file.close if file
end
return locked
end
if $0 == __FILE__
p locked?("test.txt")
end