国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

Ruby中的異常處理代碼編寫示例

2019-10-26 19:28:24
字體:
來源:轉載
供稿:網友

單個異常使用 fail 關鍵字僅僅當捕獲一個異常并且反復拋出這個異常(因為這里你不是失敗,而是準確的并且故意拋出一個異常)。

  begin   fail 'Oops'  rescue => error   raise if error.message != 'Oops'  end

    不要為 fail/raise 指定準確的 RuntimeError。

   

 # bad  fail RuntimeError, 'message'  # good - signals a RuntimeError by default  fail 'message'

    寧愿提供一個異常類和一條消息作為 fail/raise 的兩個參數,而不是一個異常實例。

   

 # bad  fail SomeException.new('message')  # Note that there is no way to do `fail SomeException.new('message'), backtrace`.  # good  fail SomeException, 'message'  # Consistent with `fail SomeException, 'message', backtrace`.

    不要在 ensure 塊中返回。如果你明確的從 ensure 塊中的某個方法中返回,返回將會優于任何拋出的異常,并且盡管沒有異常拋出也會返回。實際上異常將會靜靜的溜走。

  

 def foo   begin    fail   ensure    return 'very bad idea'   end  end

    Use implicit begin blocks when possible.如果可能使用隱式 begin 代碼塊。

   

 # bad  def foo   begin    # main logic goes here   rescue    # failure handling goes here   end  end  # good  def foo   # main logic goes here  rescue   # failure handling goes here  end

    通過 contingency methods 偶然性方法。 (一個由 Avdi Grimm 創造的詞) 來減少 begin 區塊的使用。

 

  # bad  begin   something_that_might_fail  rescue IOError   # handle IOError  end  begin   something_else_that_might_fail  rescue IOError   # handle IOError  end  # good  def with_io_error_handling    yield  rescue IOError   # handle IOError  end  with_io_error_handling { something_that_might_fail }  with_io_error_handling { something_else_that_might_fail }

    不要抑制異常輸出。

 

  # bad  begin   # an exception occurs here  rescue SomeError   # the rescue clause does absolutely nothing  end  # bad  do_something rescue nil

    避免使用 rescue 的修飾符形式。

   

 # bad - this catches exceptions of StandardError class and its descendant classes  read_file rescue handle_error($!)  # good - this catches only the exceptions of Errno::ENOENT class and its descendant classes  def foo   read_file  rescue Errno::ENOENT => ex   handle_error(ex)  end

    不要用異常來控制流。

   

 # bad  begin   n / d  rescue ZeroDivisionError   puts "Cannot divide by 0!"  end  # good  if d.zero?   puts "Cannot divide by 0!"  else   n / d  end            
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 盐津县| 静乐县| 巢湖市| 临沧市| 洛浦县| 松原市| 平和县| 蓬安县| 项城市| 双流县| 会东县| 延津县| 天气| 勐海县| 宜宾市| 光山县| 阿鲁科尔沁旗| 南充市| 德惠市| 威远县| 扶风县| 高唐县| 高青县| 马边| 偏关县| 洞头县| 巴林左旗| 富裕县| 邵武市| 嵊泗县| 洮南市| 革吉县| 宜城市| 安新县| 光山县| 南雄市| 宜兰市| 辛集市| 固阳县| 夏邑县| 兰溪市|