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 ...
随机推荐
- ASP.NET MVC Controller Session问题
发现问题 最近在项目中遇到这样一个问题,一直没办法重现,所以几天都没有解决. 测试那边给出的问题是这样的:每天早上来的时候,第一次通过单点登录到系统的时候,总会跳转回登录界面,再次登录就好了.当时给我 ...
- 第十一课:js操作选择器的通用函数
1.判断文档是否是XML文档 var isXML = function(elem){ var documentElement = elem && (elem.ownerDocument ...
- javascript键盘输入控制
获取键盘控制事件 document.onkeydown = keyDown 当浏览器读到这个语句时,无论按下键盘上的哪个键,都将呼叫KeyDown()函数. 不同浏览器的实现: Netscape Ne ...
- openvpn的介绍和搭建过程
本文摘自:http://www.linuxidc.com/Linux/2012-01/51702.htm,在这只是为了做个笔记使用
- sort+awk+uniq三者结合使用
(1)统计文件中出现次数最多的前10个单词 #ps -ef > ps.file #cat ps.file | awk ‘{print $1}’ | sort | uniq -c | sort - ...
- 【POJ 1273】Drainage Ditches(网络流)
一直不明白为什么我的耗时几百毫秒,明明差不多的程序啊,我改来改去还是几百毫秒....一个小时后:明白了,原来把最大值0x3f(77)取0x3f3f3f3f就把时间缩短为16ms了.可是为什么原来那样没 ...
- hdu 3068 最长回文子串 TLE
后缀数组+RMQ是O(nlogn)的,会TLE..... 标准解法好像是马拉车,O(n).... #include "algorithm" #include "cstdi ...
- C++中尖括号和引号的区别---转载
如果你还看一些别的C++教程,那么你可能很早就发现了,有些书上的#include命令写作#include <文件名>,但有时候又会出现#include "文件名".你会 ...
- HTTPS-能否避免流量劫持
流量劫持是什么? EtherDream在一篇科普文章<>中详细介绍了流量劫持途径和方式. 流量劫持是一种古老的攻击方式,比如早已见惯的广告弹窗等,很多人已经对此麻木,并认为流量劫持不会造成 ...
- 常用数据库 JDBC URL 格式
一 常用数据库 JDBC URL 格式 1 sqLite 驱动程序包名:sqlitejdbc-v056.jar 驱动程序类名: org.sqlite.JDBC JDBC URL: jdbc:sqli ...