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 ...
随机推荐
- SequoiaDB 系列源码分析调整
犹豫我经验尚不够丰富,有大牛跟我说,以我这样定下的结构来分析源码,学习效果不太好. 应该先从程序的进程入口函数开始,慢慢的跟流程来分析.先通过系统的启动.退出来分析所用到的技术,像进程模型,线程模型等 ...
- [代码片段]javascript检查图片大小和格式
function checkImgType(input) { var this_ = document.getElementsByName('imgFile')[0]; var filepath = ...
- msf命令全集
一.msfconsole ? 帮助菜单 back 从当前环境返回 banner 显示一个MSF banner cd 切换目录 color 颜色转换 connect 连接一个主机 e ...
- 【BZOJ 3524】【Poi2014】Couriers 可持久化线段树
为什么这个主席树叫可持久化线段树,我不知道,具体得问达神.我无限T,然后DaD3zZ一针见血地指出了我的N*50爆内存导致无限编译超时O)ZO)ZO)Z真是太神啦.以图为鉴: 达神题解传送门:http ...
- Mysql-提示java.sql.SQLException: Cannot convert value '0000-00-00 00:00:00' from column 7 to TIMESTAMP.
在Mysql数据库中使用DATETIME类型来存储时间,使用JDBC中读取这个字段的时候,应该使用 ResultSet.getTimestamp(),这样会得到一个java.sql.Timestamp ...
- Java-Stack
package 集合类.list类; import java.util.Date; import java.util.Stack; /** * stack类继承与vector类 * @author j ...
- Oracle使用JDBC进行增删改查
数据库和表 create table USERS( USERNAME VARCHAR2(20) not null, PASSWORD VARCHAR2(20))alter table USERS ...
- 最大ASCII的和问题
问题:One day when you are going to clear all your browsing history, you come up with an idea: You want ...
- poj 3233 矩阵快速幂+YY
题意:给你矩阵A,求S=A+A^1+A^2+...+A^n sol:直接把每一项解出来显然是不行的,也没必要. 我们可以YY一个矩阵: 其中1表示单位矩阵 然后容易得到: 可以看出这个分块矩阵的左下角 ...
- [转] 计算几何模板Orz
#include<math.h> #define MAXN 1000 #define offset 10000 #define eps 1e-8 #define PI acos(-1.0) ...