Ruby Exceptions — Why “else”?

前端 未结 5 2061
长情又很酷
长情又很酷 2021-01-31 14:11

I\'m trying to understand exceptions in Ruby but I\'m a little confused. The tutorial I\'m using says that if an exception occurs that does not match any of the exceptions iden

5条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-31 14:40

    Thanks to else you sometimes can merge two nested begin end blocks.
    So (simplified example from my current code) instead of:

      begin
        html = begin
          NetHTTPUtils.request_data url
        rescue NetHTTPUtils::Error => e
          raise unless 503 == e.code
          sleep 60
          retry
        end
        redo unless html["market"]
      end
    

    you write:

      begin
        html = NetHTTPUtils.request_data url
      rescue NetHTTPUtils::Error => e
        raise unless 503 == e.code
        sleep 60
        retry
      else
        redo unless html["market"]
      end
    

提交回复
热议问题