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

标签: Rubyexception异常处理
584人阅读 评论(0) 收藏 举报
分类:
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


1
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:386278次
    • 积分:6353
    • 等级:
    • 排名:第4108名
    • 原创:228篇
    • 转载:0篇
    • 译文:5篇
    • 评论:157条
    博客专栏