1. 程式人生 > >[2]ruby&ruby on rails入門筆記---Ruby中的異常

[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----" 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