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!

时间: 2024-10-23 18:29:51

ruby Errors & Exceptions的相关文章

.Net Core 项目开发中的Errors,Exceptions

这个错误是在连接数据库的时候,没有找到对应的表, namespace TodoApi.Models { public class TodoContext : DbContext { public TodoContext(DbContextOptions<TodoContext> options) : base(options) { } public DbSet<ABBDevice> ABBDevice { get; set; } //这个名称,必须要和数据库中的表名保持一致,才能找

深入剖析 Spring 框架的 BeanFactory

说到Spring框架,人们往往大谈特谈一些似乎高逼格的东西,比如依赖注入,控制反转,面向切面等等.但是却忘记了最基本的一点,Spring的本质是一个bean工厂(beanFactory)或者说bean容器,它按照我们的要求,生产我们需要的各个各样的bean,提供给我们使用.只是在生产bean的过程中,需要解决bean之间的依赖问题,才引入了依赖注入(DI)这种技术.也就是说依赖注入是beanFactory生产bean时为了解决bean之间的依赖的一种技术而已. 那么我们为什么需要Spring框架

Customizing Site-Wide Behavior for ASP.NET Web Pages (Razor) Sites

By Tom FitzMacken|February 17, 2014 This article explains how to make site-side settings for pages in an ASP.NET Web Pages (Razor) website. What you'll learn: How to run code that lets you set values (global values or helper settings) for all pages i

Stream Player control

In this article you will find an implementation of a stream player control. Download WPF demo - 11 MB Download WinForms demo - 11 MB Download WPF sources - 11 MB Download WinForms sources - 11 MB Download FFmpeg facade sources - 16.8 KB Introduction

Spring中Bean的生命中期与InitializingBean和DisposableBean接口

Spring提供了一些标志接口,用来改变BeanFactory中的bean的行为.它们包括InitializingBean和DisposableBean.实现这些接口将会导致BeanFactory调用前一个接口的afterPropertiesSet()方法,调用后一个接口destroy()方法,从而使得bean可以在初始化和析构后做一些特定的动作. 在内部,Spring使用BeanPostProcessors 来处理它能找到的标志接口以及调用适当的方法.如果你需要自定义的特性或者其他的Sprin

_AppStart.cshtml 和 _PageStart.cshtml的妙用

Customizing Site-Wide Behavior for ASP.NET Web Pages (Razor) Sites By Tom FitzMacken|February 17, 2014 Print This article explains how to make site-side settings for pages in an ASP.NET Web Pages (Razor) website. What you'll learn: How to run code th

Powershell错误处理,try catch finally

脚本的调试向来是一个艰巨的任务,在powershell出现以前简直是一场灾难.在powershell中微软终于做出了诸多改进,不但有了$Error.-whatif,也有了ISE.而在语法上也增加了try-catch-finally,终于可以便利的进行调试和错误处理了.在该语法中,finally并不是必需的,但是个人并不建议去掉该部分.建议将功能的预处理放在try部分,但没有错误时,再在finally完成功能.下面将用一段代码演示如何进行错误处理.主要功能是将一段字符串写道硬盘上一个新建的文件中,

Parallel Processing and Concurrency in the .NET Framework

http://msdn.microsoft.com/en-us/library/hh156548(v=vs.110).aspx The .NET Framework provides several ways for you to use multiple threads of execution to keep your application responsive to your user while maximizing the performance of your user's com

Factory(springBean)

spring中的BeanFactory 我们常把spring看作一个bean工厂或者ioc容器,他帮助我们负责对象的创建管理,以及对象键间依赖关系的建立. 关于工厂的实现,一般来说就是BeanFactory和ApplicationContext两种实现方式,前者是所有实现的父类,Application继承于它. 那么我们为什么需要Spring框架来给我们提供这个beanFactory的功能呢?原因是一般我们认为是,可以将原来硬编码的依赖,通过Spring这个beanFactory这个工长来注入依