def first_line( filename ) begin file = open("some_file") info = file.gets file.close info # Last thing evaluated is the return value rescue nil # Can't read the file? then don't return a string end end
有时我们会希望围绕问题展开创造性工作.这里,如果文件不存在,我们用标准输入代替:
begin file = open("some_file") rescue file = STDIN end begin # ... process the input ... rescue # ... and deal with any other exceptions here. end
retry 用于 rescue 代码表示又重新执行 begin 代码.这让我们可以压缩前面的例子:
fname = "some_file" begin file = open(fname) # ... process the input ... rescue fname = "STDIN" retry end