ruby Errors & Exceptions

时间:2023-02-23 10:16:15

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的更多相关文章

  1. &period;Net Core 项目开发中的Errors&comma;Exceptions

    这个错误是在连接数据库的时候,没有找到对应的表, namespace TodoApi.Models { public class TodoContext : DbContext { public To ...

  2. Handling Errors and Exceptions

    http://delphi.about.com/od/objectpascalide/a/errorexception.htm Unfortunately, building applications ...

  3. XmlValidationHelper XSD、Schema&lpar;XmlSchemaSet&rpar;、XmlReader&lpar;XmlValidationSettings&rpar;、XmlDocument、XDocument Validate

    namespace Test { using Microshaoft; using System; using System.Xml; using System.Xml.Linq; class Pro ...

  4. 招聘&period;NET开发人员&lpar;截止于2015-06-15&rpar;

    文章更新 2015-06-15 01:00AM: 感谢各位的支持,简历和解决方案接收截止.2015-06-08 08:30AM: 已经收到一些简历和解决方案,正在筛选中.职位仍然开放,欢迎发送简历及解 ...

  5. 算法设计和数据结构学习&lowbar;5&lpar;BST&amp&semi;AVL&amp&semi;红黑树简单介绍&rpar;

    前言: 节主要是给出BST,AVL和红黑树的C++代码,方便自己以后的查阅,其代码依旧是data structures and algorithm analysis in c++ (second ed ...

  6. Stream Player control

    In this article you will find an implementation of a stream player control. Download WPF demo - 11 M ...

  7. 深入剖析 Spring 框架的 BeanFactory

    说到Spring框架,人们往往大谈特谈一些似乎高逼格的东西,比如依赖注入,控制反转,面向切面等等.但是却忘记了最基本的一点,Spring的本质是一个bean工厂(beanFactory)或者说bean ...

  8. Task-based Asynchronous Pattern &lpar;TAP&rpar;

    The Task-based Asynchronous Pattern (TAP) is based on the System.Threading.Tasks.Task and System.Thr ...

  9. 【JS】Advanced1:Object-Oriented Code

    Object-Oriented Code 1. var Person = function (name) { this.name = name; }; Person.prototype.say = f ...

随机推荐

  1. ERR&lowbar;CONTENT&lowbar;DECODING&lowbar;FAILED错误的原因和解决办法

    1. ERR_CONTENT_DECODING_FAILED错误的原因 这种错误通常发生于Http请求中的头部信息标识内容是gzip编码的,但实际上不是. 2. ERR_CONTENT_DECODIN ...

  2. Creating a SharePoint Sequential Workflow

    https://msdn.microsoft.com/en-us/library/office/hh824675(v=office.14).aspx Creating a SharePoint Seq ...

  3. const限定符

    1 const的作用 便于进行类型检查.可以保护被修饰的东西.避免不必要的内存分配.为函数重载提供一个参考. 2 const成员函数 const成员函数只能访问数据成员的值,而不能修改他. #incl ...

  4. MVC中使用WebMail 发送注册验证信息

    在MVC中发送Email 可以使用WebMail :使用起来十分简单.如下: WebMail.SmtpServer = ConfigurationHelper.GetValue("SmtpS ...

  5. SVN 代码下载,上传

    代码下载,如: svn co https://99.99.16.1:8080/svn/pavenas/webpy --username bg 代码上传,如: svn commit -m "备 ...

  6. ES6学习笔记&colon;Module的基本用法

    export和import ES6实现了模块功能,试图解决JavaScript代码上的依赖和部署上的问题,取代现有的CommonJs的AMD规范,成为浏览器和服务器通用的模块解决方案. 模块功能有两个 ...

  7. Android常用动画Animation的使用

    Andriod中有几种常用的Animation AlphaAnimation  淡入淡出效果 RotateAnimation 旋转效果 ScaleAnimation 缩放动画 TranslaAnima ...

  8. logrotate日志轮转配置文档

    转自:http://blog.163.com/bull_linux/blog/static/2138811422013101334544349/ 使用:    logrotate CONF_FILE+ ...

  9. cocos2d-x 混合模式

    在OpenGL(ES),使用glBlendFunc函数实现实现混合模式,cocos2d-x中可以使用BlendFunc. 什么是颜色混合?简单来说就是将RGBA中的A,经行操作处理.具体一点,就是把某 ...

  10. 「Algospot」量化QUANTIZE

    一道不难的DP题,主要是为了总结这类最优化题的思路:同时还学到了一个新操作 传送门:$>here<$ 题意 给出一个长度为$N$的序列,要求最多使用s个数字进行量化(有损压缩),即代替原数 ...