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

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----"
if file
puts "-----222222----"
puts "File opened successfully"
end
rescue
puts "-----exceptions----"
file = STDIN
end
print file , "==" , 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" )
if file
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.'
rescue Exception => e
puts e .message
puts e .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"
rescue Exception => e
puts e .message
puts e .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"
def promptAndGet ( prompt )
print prompt
res = readline.chomp
throw :quitRequested if res == "!"
return res
end
puts "111111111111111111111111111111111111"
catch :quitRequested do
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

class FileSaveError < NoMemoryError
attr_reader :reason
def initialize ( 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----"
raise FileSaveError .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


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值