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 ...
随机推荐
- mysql基础 事务的认识和使用
事务(Transaction)是访问并可能更新数据库中各种数据项的一个程序执行单元(unit).事务是恢复和并发控制的基本单位. 在关系数据库中,一个事务可以是一条SQL语句,一组SQL语句或整个程序 ...
- sql 随机函数newid()
newid()返回的是uniqueidentifier类型的唯一值.newid()每次产生的值都不一样 从表中随机获取前N条记录 select top N * from table_name ord ...
- CSS3——动画效果
CSS3动画在Style里面就实现了以往我们用JQ写的动画效果,着实简便了不少~ 简单Demo: html代码: <div id="dv1"></div> ...
- Calender的使用详解
Calendar和GregorianCalendar简介 Calendar的中文翻译是日历,实际上,在历史上有着许多种计时的方法.所以为了计时的统一,必需指定一个日历的选择.那现在最为普及和通用的日历 ...
- User Attributes - Inside Active Directory
User Attributes - Inside Active Directory Related to the book Inside Active Directory, ISBN 0-201-61 ...
- Vijos p1892 树上的最大匹配 树形DP+计数 被卡常我有特殊技巧heheda
https://vijos.org/p/1892 此题需要手动开栈: <<; //256MB char *p=(char*)malloc(size)+size; __asm__(" ...
- poppin_xpower_ 常城
- hdu4547 lca tarjan
比较直接. #include<map> #include<queue> #include<stack> #include<cmath> #include ...
- 【POJ 1416】Shredding Company
题 题意 给你一个target number,和一个最多六位的数num,让你把数分段,使总和最接近但不大于target number. 如果只有一种方法就输出总和.分段,如果有多种方法,输出rejec ...
- BRIEF算法
本文结构 为了看懂ORB特征提取算法,来看了BRIEF算法的原文,并查看了OpenCV中BRIEF的相关实现,来验证论文的解读正确与否. BRIEF论文解读 摘要 用二进制串描述局部特征,好处有二:一 ...