ruby Errors & Exceptions
2016-05-08 12:07
567 查看
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:
Both errors were triggered by the same line of code. Each is a totally different error message, though.
The first,
The second,
Here, there’s a good chance that
Because these errors were meaningful errors, they allowed you to debug your program painlessly, and ideally also provided a learning opportunity.
All errors inherit their functionality from the
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
This means that if you’ve got a custom error that you’d like to create, like an
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
Easy enough. Now you know that you can raise this
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.
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.
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
Now, if the correct password was entered, the funds are removed as expected.
But this time, if the incorrect password is entered, your new
That’s so useful!
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
oneis 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
Fixnumto a
String.
Here, there’s a good chance that
oneis 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 thatNameErrorand
TypeErrorare simply the class names for these errors!
All errors inherit their functionality from the
Exceptionclass.
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
NameErrorand
TypeError.
This means that if you’ve got a custom error that you’d like to create, like an
InvalidPasswordError, 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
raisekeyword.
raise InvalidPasswordError InvalidPasswordError: InvalidPasswordError
Easy enough. Now you know that you can raise this
InvalidPasswordErrorwhenever 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
InvalidPasswordErrorin 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
InvalidPasswordErroris 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!
相关文章推荐
- ruby Errors & Exceptions
- ruby Inheritance
- 使用深度搜索分析心理调查问卷的研究
- 小白在MAC安装ruby环境以及下载和安装CocoaPods
- MacOS搭建Ruby环境
- 应用ruby打造个性化的有道单词本 (二)
- 应用ruby打造个性化的有道单词本 (一)
- Ruby--正则
- 解决ubuntu中新建rails程序无法打开ruby内置服务器问题!
- Ruby RestClient learning note
- ruby on rails中配置数据库,以及数据库与model层嫁接,增删改查详解
- 如何在Mac OS X上安装 Ruby运行环境
- windows7 安装ruby
- ruby-rails 环境搭建
- Ruby - Nokogiri 解析XML的实例
- ruby on rails ,extjs框架下的ajax使用
- ruby on rails爬坑(五):配置邮件服务器
- 淘宝的ruby镜像已无人维护,使用ruby-china的RubyGems镜像
- ruby的class << self, 及其class_eval和instance_eval的区别
- ruby 笔记