zoukankan      html  css  js  c++  java
  • ruby Errors & Exceptions

    When you first started coding, errors were probably the last thing you wanted to see.

    After all, it’s not a far stretch to associate “error” with “I messed up”.

    Hopefully by now you’ve come to appreciate the value of a good error message. Take a look at the two following errors:

    one + 3
    NameError: undefined local variable or method 'one' for main:Object
    one + 3
    TypeError: no implicit conversion of Fixnum into String

    Both errors were triggered by the same line of code. Each is a totally different error message, though.

    The first, NameError, lets you know that one is a variable that hasn’t been defined. To fix this, you’ll have to actually define the variable one.

    The second, TypeError, lets you know that you’re trying to add a Fixnum to a String.

    Here, there’s a good chance that one is a variable that is already set to a String.

    Because these errors were meaningful errors, they allowed you to debug your program painlessly, and ideally also provided a learning opportunity.

    Inheriting an Exception

    In Ruby, just about everything is an object, including errors. Turns out that NameError andTypeError are simply the class names for these errors!

    All errors inherit their functionality from the Exception class.

    There are about twenty or so default errors baked into Ruby (read more about them here) and some indicate more serious issues than others.

    Issues that deal with problems in your code (as opposed to your computer being on fire) all inherit from StandardError. This includes errors like NameError and TypeError.

    This means that if you’ve got a custom error that you’d like to create, like anInvalidPasswordError, you can easily create one by inheriting from StandardError.

    class InvalidPasswordError < StandardError
    end

    It’s really that easy. You don’t even need anything inside this class!

     

    To manually trigger an exception or error, which can be described as “raising” or “throwing” an exception, use the raise keyword.

    raise InvalidPasswordError
    InvalidPasswordError: InvalidPasswordError

    Easy enough. Now you know that you can raise this InvalidPasswordError whenever it’s appropriate.

    May I suggest you use it when a password is… invalid?

    But this still isn’t super descriptive. Luckily, you can raise an error with an additional message.

    raise InvalidPasswordError, "The password you entered is invalid."
    InvalidPasswordError: The password you entered is invalid.

    That’s more like it. Now it’s explicit what went wrong when this particular exception was thrown.

    This is by no means a comprehensive guide to throwing errors and exceptions.

    This material could fill a course by itself, and it is a topic we will return to later in this material.

    This is, however, the most common way you’ll see exceptions and errors being thrown in the wild.

    Exceptional Errors

    When other developers are using your code, it’s a good idea to bake meaningful errors right into your public API.

    Let’s see how you might be able to use this InvalidPasswordError in the context of the examples from earlier in the lesson.

    class InvalidPasswordError < StandardError
    end
    
    class Customer
      attr_reader :funds
    
      def initialize(funds, password)
        @password = password
        @funds = funds
      end
    
      def withdraw_securely(amount, password)
        if password == @password
          remove_funds(amount)
        else
          raise InvalidPasswordError, "'#{password}' is not the correct password."
        end
      end
    
      private
    
      def remove_funds(amount)
        @funds -= amount
      end
    end

    Now, if the correct password was entered, the funds are removed as expected.

    But this time, if the incorrect password is entered, your new InvalidPasswordError is thrown with a useful little message.

    kim = Customer.new(1000, "coolpassword")
    # => #<Customer:0x007faabc8012b8 @password="coolpassword", @funds=1000>
    kim.withdraw_securely(200, "coolpassword")
    # => 800
    kim.withdraw_securely(150, "badpassword")
    InvalidPasswordError: 'badpassword' is not the correct password.

    That’s so useful!

  • 相关阅读:
    编写一个供浏览器端使用的NPM包
    针对低网速的性能优化
    前端性能优化之WebP
    Openwrt自定义CGI实现
    论用户体验测试:牛逼的功能千篇一律,好的用户体验万里挑一
    Vue 依赖收集原理分析
    怎么去写好一段优雅的程序
    hdu 1085 有num1个 1 ,num2个 2 ,num3个 5 (母函数)
    hdu 1398 整数划分变形 (母函数)
    hdu 1028 整数划分 (母函数)
  • 原文地址:https://www.cnblogs.com/iwangzheng/p/5470209.html
Copyright © 2011-2022 走看看