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 ...
随机推荐
- ArcGIS中的北京54和西安80投影坐标系详解
ArcGIS中的北京54和西安80投影坐标系详解 1.首先理解地理坐标系(Geographic coordinate system),Geographic coordinate system直译为地理 ...
- Moqui学习之代码分析mantle priceServices.xml
<?xml version="1.0" encoding="UTF-8"?> <!-- This software is in the pub ...
- Nginx 配置详解
http://www.cnblogs.com/analyzer/articles/1377684.html 本文转自:http://blog.c1gstudio.com/archives/434 推荐 ...
- javascript键盘输入控制
获取键盘控制事件 document.onkeydown = keyDown 当浏览器读到这个语句时,无论按下键盘上的哪个键,都将呼叫KeyDown()函数. 不同浏览器的实现: Netscape Ne ...
- mysql-函数FOUND_ROWS()
FOUND_ROWS() SELECT语句中经常可能用LIMIT限制返回行数.有时候可能想要知道如果没有LIMIT会返回多少行,但又不想再执行一次相同语句.那么,在SELECT查询中包含SQL_CAL ...
- yii2URL美化
yii2的url 域名/index.php?r=site%2Findex 实际为 域名/index.php?r=site/index 可以美化下 可以在main.php中配置 'components' ...
- Erlang之父的学习历史及学习建议
当我开始学习编程的时候(1967年),我可以在 FORTRAN 和(传说中的)Algol 之间选择,不过没有任何人了解 Algol,所以我选择了 FORTRAN. 在我最早学习编程的时候,我的编程周期 ...
- 在纯HTML的静态网页中添加一段统计网页访问量的JAVA Script代码?
如何在网站上进行流量统计呢,可以找第三方服务网站去注册,但也可以在网站上直接添加代码,只需将以下代码copy到你的网页中,复制到</body>之前就可以啦!是不是很简单啊! <scr ...
- (Beta)Let's-版本发布说明
Let's App(Beta)现已隆重上市 GIT源码请戳此处 版本的新功能 我们在这一版本对于项目的规划目标主要集中在三个方面——预约用户观感,完善功能链条,改善用户体验 界面 首先,在β阶 ...
- HTTPS 协议降级攻击原理
0x00 HTTPS 在传统流行的web服务中,由于http协议没有对数据包进行加密,导致http协议下的网络包是明文传输,所以只要攻击者拦截到http协议下的数据包,就能直接窥探这些网络包的数据. ...