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

2016-11-11 20:04:49来源:CSDN作者:chancein007人点击

第七城市
Ruby中异常处理非常的重要,Ruby中异常处理,包括Exception 捕获,Retry,Raise,ensure ,Else格式,Throw...Catch已经类级别的异常。其具体格式和用法如下。1. Exception 捕获,其格式如下,和Java中的try...catch...finally有的一拼begin# -rescue OneTypeOfException# -rescue AnotherTypeOfException# -else# Other exceptionsensure# Always will be executedend--------Sample------beginfile= open("/unexistant_file")puts"-----1111111----"iffileputs"-----222222----"puts"File opened successfully"endrescueputs"-----exceptions----"file=STDINendprintfile,"==",STDIN,"/n"-----------输出结果------------------exceptions----#<IO:0x22703d0>==#<IO:0x22703d0>
2. Retrybegin# Exceptions raised by this code will# be caught by the following rescue clauserescue# This block will capture all types of exceptionsretry # This will move control to the beginning of beginend--------Sample------beginputs"Try to open file"file= open("/unexistant_file")iffileputs"File opened successfully"endrescuefname="existant_file"puts"Begin to retry"retryend-----------输出结果会有无限的循环-------------Try to open fileBegin to retryTry to open fileBegin to retryTry to open fileBegin to retry。。。。。
3.Raise 相当于java中的throw 关键字,自己显式抛出异常raiseORraise "Error Message"ORraise ExceptionType, "Error Message"ORraise ExceptionType, "Error Message" condition
beginputs 'I am before the raise.'raise 'An error has occurred.'puts 'I am after the raise.'rescueputs 'I am rescued.'endputs '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 exceptionrescue#.. handle errorensure#.. finally ensure execution#.. This will always execute.end
beginraise'A test exception.'rescueException=>eputse.messageputse.backtrace.inspectensureputs"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 exceptionrescue# .. handle errorelse#.. executes if there is no exceptionensure#.. finally ensure execution#.. This will always execute.end--------Sample Code-----------begin# raise'A test exception.'puts"I'm not raising exception"rescueException=>eputse.messageputse.backtrace.inspectelseputs"Congratulations-- no errors!"ensureputs"Ensuring execution"end-----------输出结果如下-------------I'm not raising exceptionCongratulations-- no errors!Ensuring execution
6. Throw...Catch 用来跳出循环,这个和Java的try catch有点区别throw :lablename#.. this will not be executedcatch :lablename do#.. matching catch will be executed after a throw is encountered.endORthrow :lablename condition#.. this will not be executedcatch :lablename do#.. matching catch will be executed after a throw is encountered.end--------------Sample----------------puts"catchcatchcatchcatchcatchcatchcatchcatchcatchcatchcatchcatchcatch"defpromptAndGet(prompt)printpromptres= readline.chompthrow:quitRequestedifres=="!"returnresendputs"111111111111111111111111111111111111"catch:quitRequesteddoputs"2222222222222222222222222222222"name= promptAndGet("Name: ")puts"333333333333333333333333333333"age= promptAndGet("Age: ")puts"444444444444444444444444444"sex= promptAndGet("Sex: ")puts"5555555555555555555555555555"# ..# process informationendpromptAndGet("Name1:")-----------输出结果如下-------------catchcatchcatchcatchcatchcatchcatchcatchcatchcatchcatchcatchcatch1111111111111111111111111111111111112222222222222222222222222222222Name: Rodney333333333333333333333333333333Age: 33444444444444444444444444444Sex: Male5555555555555555555555555555Name1:HenryProcess finished with exit code 0
7. Class级别的异常Ruby's standard classes and modules raise exceptions. All the exception classesform a hierarchy, with the class Exception at the top. The next level containsseven different types: Interrupt NoMemoryError SignalException ScriptError StandardError SystemExit
classFileSaveError<NoMemoryErrorattr_reader:reasondefinitialize(reason)@reason=reasonendend
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----"endend-----------输出结果如下-------------C:/RailsInstaller/Ruby2.2.0/bin/ruby.exe -e $stdout.sync=true;$stderr.sync=true;load($0=ARGV.shift) D:/ruby/learnruby/class_exception.rbD:/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

第七城市

最新文章

123

最新摄影

微信扫一扫

第七城市微信公众平台