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!
ruby Errors & Exceptions的更多相关文章
- .Net Core 项目开发中的Errors,Exceptions
这个错误是在连接数据库的时候,没有找到对应的表, namespace TodoApi.Models { public class TodoContext : DbContext { public To ...
- Handling Errors and Exceptions
http://delphi.about.com/od/objectpascalide/a/errorexception.htm Unfortunately, building applications ...
- XmlValidationHelper XSD、Schema(XmlSchemaSet)、XmlReader(XmlValidationSettings)、XmlDocument、XDocument Validate
namespace Test { using Microshaoft; using System; using System.Xml; using System.Xml.Linq; class Pro ...
- 招聘.NET开发人员(截止于2015-06-15)
文章更新 2015-06-15 01:00AM: 感谢各位的支持,简历和解决方案接收截止.2015-06-08 08:30AM: 已经收到一些简历和解决方案,正在筛选中.职位仍然开放,欢迎发送简历及解 ...
- 算法设计和数据结构学习_5(BST&AVL&红黑树简单介绍)
前言: 节主要是给出BST,AVL和红黑树的C++代码,方便自己以后的查阅,其代码依旧是data structures and algorithm analysis in c++ (second ed ...
- Stream Player control
In this article you will find an implementation of a stream player control. Download WPF demo - 11 M ...
- 深入剖析 Spring 框架的 BeanFactory
说到Spring框架,人们往往大谈特谈一些似乎高逼格的东西,比如依赖注入,控制反转,面向切面等等.但是却忘记了最基本的一点,Spring的本质是一个bean工厂(beanFactory)或者说bean ...
- Task-based Asynchronous Pattern (TAP)
The Task-based Asynchronous Pattern (TAP) is based on the System.Threading.Tasks.Task and System.Thr ...
- 【JS】Advanced1:Object-Oriented Code
Object-Oriented Code 1. var Person = function (name) { this.name = name; }; Person.prototype.say = f ...
随机推荐
- 获取Web.config配置节
static string GetAppSetting(string key) { var appSetting = ConfigurationManager.AppSettings[key]; if ...
- iOS开发小技巧--利用运行时得到隐藏的成员变量
一.关于运行时,已经从网络上摘抄了一片文章,这里只有项目中自己的简单使用 -- 查找隐藏的成员变量 导入头文件 可以获得隐藏的成员变量,方法,属性等 代码: 打印效果图:
- 虚拟机 vlan trunk 特性
1. 功能 1)允许不同vlan的network下的虚拟机之间通信.一般情况下,虚拟机只能在相同vlan的网络下通信. 2)允许虚拟机发送vlan报文. 2. 组网图 虚拟机出来的tap设备连接到tb ...
- 【CodeForces 227A】Where do I Turn?叉积
题意 ABC的位置关系只有三种可能: 1.在一条直线上,输出TOWARDS A--B--C 2.AB 和BC垂直,B为直角顶点,AB左侧是C,输出LEFT C--B | A 3.AB 和BC垂直,B为 ...
- 【CodeForces 520E】Pluses everywhere
题意 n个数里插入k个+号,所有式子的和是多少(取模1000000007) (0 ≤ k < n ≤ 105). 分析 1.求答案,考虑每个数作为i位数(可为答案贡献10的i-1次方,个位i=1 ...
- LinkedHashMap实现LRU算法
LinkedHashMap特别有意思,它不仅仅是在HashMap上增加Entry的双向链接,它更能借助此特性实现保证Iterator迭代按照插入顺序(以insert模式创建LinkedHashMap) ...
- jquery中的prop和attr比较区别
近期和一同事争执prop和attr的区别,也查了很多,同事说它只是特性和固有属性的区别,但是我也查到了一些其他的,故此,来总结一下吧! 1.固有属性和特别属性 对于HTML元素本身就带有的固有属性,在 ...
- TCP/IP详解 学习三
网际协议 ip Ip 是不可靠和无连接的 ip首部 4个字节的 32 bit值以下面的次序传输:首先是 0-7 bit,其次 8-15 bit,然后 1 6-23 bit,最后是 24~31 bit. ...
- jQuery的插入
append(content) 概述 : 向每个匹配的元素内部追加内容. 这个操作与对指定的元素执行appendChild方法,将它们添加到文档中的情况类似 append(function(index ...
- php中图片文件的导入,上传与下载
---------------------------------------------图片的导入-------------------------------------------------- ...