Ruby中异常处理非常的重要,Ruby中异常处理,包括Exception 捕获,Retry,Raise,ensure ,Else格式,Throw...Catch已经类级别的异常。其具体格式和用法如下。
1. Exception 捕获,其格式如下,和Java中的try...catch...finally有的一拼
begin
# -
rescue OneTypeOfException
# -
rescue AnotherTypeOfException
# -
else
# Other exceptions
ensure
# Always will be executed
end
--------Sample------
begin
file= open("/unexistant_file")
puts"-----1111111----"
iffile
puts"-----222222----"
puts"File opened successfully"
end
rescue
puts"-----exceptions----"
file=STDIN
end
printfile,"==",STDIN,"\n"
-----------输出结果-------------
-----exceptions----
#<IO:0x22703d0>==#<IO:0x22703d0>
2. Retry
begin
# Exceptions raised by this code will
# be caught by the following rescue clause
rescue
# This block will capture all types of exceptions
retry # This will move control to the beginning of begin
end
--------Sample------
begin
puts"Try to open file"
file= open("/unexistant_file")
iffile
puts"File opened successfully"
end
rescue
fname="existant_file"
puts"Begin to retry"
retry
end
-----------输出结果会有无限的循环-------------
Try to open file
Begin to retry
Try to open file
Begin to retry
Try to open file
Begin to retry
。。。。。
3.Raise 相当于java中的throw 关键字,自己显式抛出异常
raise
OR
raise "Error Message"
OR
raise ExceptionType, "Error Message"
OR
raise ExceptionType, "Error Message" condition
begin
puts 'I am before the raise.'
raise 'An error has occurred.'
puts 'I am after the raise.'
rescue
puts 'I am rescued.'
end
puts 'I am after the begin block.'
------------------------------------------
I am before the raise.
I am rescued.
I am after the begin block.
4.ensure 相当于java中的finally语句
begin
#.. process
#..raise exception
rescue
#.. handle error
ensure
#.. finally ensure execution
#.. This will always execute.
end
begin
raise'A test exception.'
rescueException=>e
putse.message
putse.backtrace.inspect
ensure
puts"Ensuring execution"
end
-----------输出结果如下-------------
A test exception.
["D:/ruby/learnruby/exception_test.rb:28:in `<top (required)>'", "-e:1:in `load'", "-e:1:in `<main>'"] Ensuring execution
5. Else格式 Else用在异常语句中的情形是,当没有exception抛出来的时候
begin
#.. process
#..raise exception
rescue
# .. handle error
else
#.. executes if there is no exception
ensure
#.. finally ensure execution
#.. This will always execute.
end
--------Sample Code-----------
begin
# raise'A test exception.'
puts"I'm not raising exception"
rescueException=>e
putse.message
putse.backtrace.inspect
else
puts"Congratulations-- no errors!"
ensure
puts"Ensuring execution"
end
-----------输出结果如下-------------
I'm not raising exception
Congratulations-- no errors!
Ensuring execution
6. Throw...Catch 用来跳出循环,这个和Java的try catch有点区别
throw :lablename
#.. this will not be executed
catch :lablename do
#.. matching catch will be executed after a throw is encountered.
end
OR
throw :lablename condition
#.. this will not be executed
catch :lablename do
#.. matching catch will be executed after a throw is encountered.
end
--------------Sample----------------
puts"catchcatchcatchcatchcatchcatchcatchcatchcatchcatchcatchcatchcatch"
defpromptAndGet(prompt)
printprompt
res= readline.chomp
throw:quitRequestedifres=="!"
returnres
end
puts"111111111111111111111111111111111111"
catch:quitRequesteddo
puts"2222222222222222222222222222222"
name= promptAndGet("Name: ")
puts"333333333333333333333333333333"
age= promptAndGet("Age: ")
puts"444444444444444444444444444"
sex= promptAndGet("Sex: ")
puts"5555555555555555555555555555"
# ..
# process information
end
promptAndGet("Name1:")
-----------输出结果如下-------------
catchcatchcatchcatchcatchcatchcatchcatchcatchcatchcatchcatchcatch
111111111111111111111111111111111111
2222222222222222222222222222222
Name: Rodney
333333333333333333333333333333
Age: 33
444444444444444444444444444
Sex: Male
5555555555555555555555555555
Name1:Henry
Process finished with exit code 0
7. Class级别的异常
Ruby's standard classes and modules raise exceptions. All the exception classes
form a hierarchy, with the class Exception at the top. The next level contains
seven different types:
 Interrupt
 NoMemoryError
 SignalException
 ScriptError
 StandardError
 SystemExit
classFileSaveError<NoMemoryError
attr_reader:reason
definitialize(reason)
@reason=reason
end
end
File.open("input223g.txt","r")do|file|
begin
# Write out the data ...
puts"File can be opened!!!!"
raise'A test exception.'
rescue
# Something went wrong!
puts"Error happend!!!!"
puts$!
puts"-----Test----"
raiseFileSaveError.new($!)
puts"-----end----"
end
end
-----------输出结果如下-------------
C:\RailsInstaller\Ruby2.2.0\bin\ruby.exe -e $stdout.sync=true;$stderr.sync=true;load($0=ARGV.shift) D:/ruby/learnruby/class_exception.rb
D:/ruby/learnruby/class_exception.rb:18:in `rescue in block in <top (required)>': FileSaveError (FileSaveError)
from D:/ruby/learnruby/class_exception.rb:9:in `block in <top (required)>'
from D:/ruby/learnruby/class_exception.rb:8:in `open'
from D:/ruby/learnruby/class_exception.rb:8:in `<top (required)>'
from -e:1:in `load'
from -e:1:in `<main>'
File can be opened!!!!
Error happend!!!!
A test exception.
-----Test----
Process finished with exit code 1

[2]rubyruby on rails入门笔记---Ruby中的异常相关推荐

  1. Python入门笔记(17):错误、异常

    一.什么是错误,什么是异常,它们两者区别 这里解释如下:个人觉得很通俗易懂 错误是指在执行代码过程中发生的事件,它中断或干扰代码的正常流程并创建异常对象.当错误中断流程时,该程序将尝试寻找异常处理程序 ...

  2. HTML入门笔记12-HTML中备注写法

    本文学习HTML中备注写法.备注,在写代码的时候非常重要,特别是写给其他人看,你可以随意打开一个网页,右键,查看源码,基本上都可以看得到前面写的HTML备注.在HTML中备注是用<!-- 这是备 ...

  3. HTML入门笔记15-HTML中插入外部链接

    本篇学习HTML中链接标签,<href>表示超链接的意思,我们来演示一次,在demo文件中点击一个文字,然后跳转到百度首页的场景. <!DOCTYPE html> <ht ...

  4. Python基础入门知识点——Python中的异常

    前言 在先前的一些章节里你已经执行了一些代码,你一定遇到了程序"崩溃"或因未解决的错误而终止的情况.你会看到"跟踪记录(traceback)"消息以及随后解释器 ...

  5. java中抛出异常快捷键_idea中处理异常的快捷键

    建议68:从System.Exception或其他常见的基本异常中派生异常 微软建议:从System.Exception或其他常见基本异常之一派生异常.在Visual Studio中输入Excepti ...

  6. ruby on rails_DB2和Ruby on Rails入门

    ruby on rails Ruby on Rails于2004年发布,已Swift成为Web应用程序开发中最流行的框架之一. 这个开源项目也称为Rails或RoR,它使用模型-视图-控制器(MVC) ...

  7. [入门]Ruby on Rails入门教程及开发工具选用

    http://witcheryne.javaeye.com/blog/846714 最近在为一家公司做一个小项目,前端时间一直在用最熟悉的java,结果java的开发效率实在让人崩溃.用框架吧-一堆配 ...

  8. onenote 入门笔记_Windows 10中的OneNote入门指南

    onenote 入门笔记 Microsoft has revamped many of its internal apps to match both the design aesthetic and ...

  9. 第四章 Rails 背后的 Ruby

    第四章 Rails 背后的 Ruby 有了第三章中的例子做铺垫,本章将为你介绍一些对 Rails 来说很重要的 Ruby 知识.Ruby 语言的知识点很多,不过对一个 Rails 开发者而言需要掌握的 ...

最新文章

  1. 微信小程序实践_4显示新闻(2)
  2. 对抽象工厂+反射+配置文件的实例理解
  3. 后台开发经典书籍--代码整洁之道
  4. docker学习------centos7.5下的swarm集群可视化构建
  5. SAP CRM市场营销表结构
  6. 创建Vue项目出错,提示vue : 无法加载文件C:\Users\xxx\AppData\Roaming\npm\vue.ps1,因为在此系统上禁止运行脚本。有关详细信息,请参阅 https:/go
  7. linux 下启动mysql
  8. 算法-低位优先的字符串排序
  9. 1200兆路由器网速_如何选购路由器才能发挥宽带的网速?
  10. linux下,保存退出vim编辑器(转)
  11. 源码解析:修改mysql密码出现错误1045
  12. android api 中文 (74)—— AdapterView.AdapterContextMenuInfo
  13. Swift 委托/代理设计模式
  14. Redis 和 memcached 区别
  15. android poi导出excel,解决java poi导出excel2003不能超过65536行的问题
  16. Python爬虫入门教程24:下载某网站付费文档保存PDF
  17. 第四章 向量代数与空间解析几何
  18. Python完全平方数
  19. 分布式异步任务框架之Celery定义、异步任务框架特点、架构、使用场景、安装配置、基本使用、多任务结构使用、延时任务、定时任务及django中使用celery
  20. ros 控制xbox_从提示框:在Windows中控制Xbox控制器,在夏天保持计算机凉爽以及DIY图书扫描装置...

热门文章

  1. 自动生成_一键自动生成CAD图纸目录
  2. 【Spring Boot】构造、访问Restful Webservice与定时任务
  3. Mysql正则表达式查询
  4. 网页打开速度很慢,怎么解决?
  5. 一只兔子每三个月生兔子JAVA,兔子生兔子问题
  6. C#打开SDE数据库的几种方式总结
  7. 自己怎么开发一个软件app、如何开发一个app系统软件?
  8. SHA-512 逻辑
  9. P2132 小Z的队伍排列-杨氏矩阵与hook定理
  10. 基于SRGAN的图像超分辨率实例