ruby - How does begin,rescue and => symbol work? -


in ruby koans, 6th exercise, there is:

def test_you_dont_get_null_pointer_errors_when_calling_methods_on_nil     # happens when call method doesn't exist.       # following begin/rescue/end code block captures exception ,     # make assertions it.      begin     nil.some_method_nil_doesnt_know_about   rescue exception => ex     # exception has been caught?     assert_equal __, ex.class      # message attached exception?     # (hint: replace __ part of error message.)     assert_match(/__/, ex.message)   end end 

i have no idea => symbol there? begin , rescue not clear me.

when goes wrong can "raise exception"

def do_it   # ..   raise exception.new("something went wrong !") if something_went_wrong end 

this stop execution of program if something_went_wrong true. , if don't handle exception.

to handle exception use "rescue exception"

begin   do_it rescue exception   puts "something went wrong, go on anyway" end 

if need work exception can give name "=>"

begin   do_it rescue exception => ex   # "ex" name of exception. , "ex.inspect" inspects it.   puts "something went wrong, #{ex.inspect}, .." end 

if ruby koans, may rubymonk online tutorial. in "ruby primer: ascent" lesson on exceptions.


Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

javascript - jQuery .height() return 0 when visible but non-0 when hidden -