On Monday 26 October 2009, Derek Smith wrote:
> |Hi All,
> |
> |I want to test if a file open failed, yet I cannot get this to work.
> |
> |attempt 1:
> |File.open( "#{RUNLOG}", "a" ) do |file| or raise StandardError ...
> |
> |
> |attempt 2
> |File.open( "#{RUNLOG}", "a" ) do |file|
> |    code here...
> |
> |
> |or raise StabdardError ...
> |end
> |
> |
> |thank you!
> |

File.open will raise an exception if the file can't be opened. The exact 
exception will depend on what actually goes wrong and will be one of the 
classes under the Errno module. Unfortunately, I don't know exactly which 
class corresponds to which error (if I remember correctly, they may also 
depend on your system). If you want to rescue all those exceptions, you can 
use SystemCallError, which is the base class for all of them. For example, you 
can do the following:

begin
  File.open("#{RUNLOG}", "a") do |file|
    ...
  end
rescue SystemCallError
  raise StandardError
end


Both your attempts couldn't work because the syntax you used was invalid. The 
correct syntax would have been this:

(File.open("#{RUNLOG}", "a") do |file|
    ...
end) or raise StandardError

The parentheses enclosing the call to File.open and its block is optional. I 
put it only for clarity. While the above syntax is correct, however, it won't 
work as you expected because File.open raises an exception when it fails. It 
would have worked if the method had returned false or nil on failure.

I hope this helps

Stefano