03 - rerunning after an exception.rb

来自「O Reilly Ruby Cookbook source code」· RB 代码 · 共 46 行

RB
46
字号
def rescue_and_retry  error_fixed = false  begin    puts 'I am before the raise in the begin block.'    raise 'An error has occurred!' unless error_fixed    puts 'I am after the raise in the begin block.'  rescue    puts 'An exception was thrown! Retrying...'    error_fixed = true    retry      end  puts 'I am after the begin block.'endrescue_and_retry# I am before the raise in the begin block.# An exception was thrown! Retrying...# I am before the raise in the begin block.# I am after the raise in the begin block.# I am after the begin block.#---require 'open-uri'def check_connection(max_tries=2, url='http://www.ruby-lang.org/')  tries = 0  begin    tries += 1    puts 'Checking connection...'    open(url) { puts 'Connection OK.' }  rescue Exception    puts 'Connection not OK!'    retry unless tries >= max_tries  endendcheck_connection# Checking connection...# Connection OK.check_connection(2, 'http://this.is.a.fake.url/')# Checking connection...# Connection not OK!# Checking connection...# Connection not OK!#---

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?