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