[2]ruby&ruby on rails入门笔记---Ruby中的异常

原创 2016年11月02日 00:32:53
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


版权声明:本文为博主原创文章,未经博主允许不得转载。

微信APP支付返回-1错误

【准备事项】 1、在微信开放平台https://open.weixin.qq.com申请新应用并拿到APPID,给这个应用申请开通支付功能并拿到商户ID。 2、在商户平台https://pay....

unity GameObject.SendMessage调用的方法有多个参数的调用方法

首先,先定义

ruby on rails 入门笔记

1. 环境搭建 ·      Ruby1.8.7+ (那么由于187p248,249的bug可能会导致Rails3崩溃,官方建议使用1.9.2的Ruby版本) ·      RubyGems ...

通过Ruby on Rails和docker构建微服务架构之入门教程

如何通过Ruby on Rails和docker构建微服务架构之入门教程

ruby on rails3 入门 ——尝鲜吧!骚年

在win下做ror开发,无疑是件痛苦的事情,运行一个命令需要瞪大半天的时间,而且环境搭建特复杂,很是不爽!不过在mac和linux上还是很快的,这也是很多rorer不屑与win下开发的主要原因吧!不过...

Ruby on Rails 和 J2EE:两者能否共存?

Ruby on Rails 是一个相对较新的 Web 应用程序框架,构建在 Ruby 语言之上。它被宣传为现有企业框架的一个替代,而它的目标,简而言之,就是让生活,至少是 Web 开发方面的生活,变...

Ruby on Rails 成长记(2)

本章主要分享安装rails虚拟运行环境,由于ruby跟运行环境的特殊性(其实就是windows太屌丝),ruby在windows上会出现奇形怪状的错误,所以我强烈建议大家能别再windows上就别再w...

关于ruby on rails测试的一些笔记

这里的rails测试主要用到了以下技术,rspec, simplecovh和factory,simplecov是用来检测测试代码对被测试代码覆盖的工具,factory_girl_rails是用来做单元...

Ruby on rails 实战圣经:Part 2: 深度剖析环境设定与Bundler

Complication is WhatHappens When You Try to Solve a Problem You Don’t Understand - Andy Boothe目录结构这一...

ruby on rails 【语法大全2】

rake 系列命令 最熟悉的就是 rake db:create/migrate 对数据库的操作, 也许这些也很少用的: rake -T 列出所有rake命令rake -T plugin ...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:[2]ruby&ruby on rails入门笔记---Ruby中的异常
举报原因:
原因补充:

(最多只允许输入30个字)