Ruby koans about_nil.rb - fr question / newbie

In programming, I am an absolute beginner . I gravitate towards a ruby ​​and created a koan. The section begins with:

def test_you_dont_get_null_pointer_errors_when_calling_methods_on_nil 

Please explain this line:

 rescue Exception => ex 

I reviewed the first two koas in this section.

+4
source share
2 answers

This line says save the code in the start-rescue block whenever it throws an exception of type Exception . It just turns out that Exception is a top-level exception that inherits all other exceptions (for example, a syntax error, a method error, etc.). Because of this, all exceptions will be saved. Then it saves this instance of the exception in the ex variable, in which you can look further (for example, backtracking, message, etc.).

I read this guide to Ruby exceptions .

An example is the following:

 begin hey "hi" rescue Exception => ex puts ex.message end #=> Prints undefined method `hey' for main:Object 

However, if the code in the initial block does not give an error, it will not go down the salvation branch.

 begin puts "hi" rescue Exception => ex puts "ERROR!" end #=> Prints "hi", and does not print ERROR! 
+2
source

Did you read the comment at the beginning of the method?

  def test_you_dont_get_null_pointer_errors_when_calling_methods_on_nil # What happens when you call a method that doesn't exist. The # following begin/rescue/end code block captures the exception and # make some assertions about it. begin nil.some_method_nil_doesnt_know_about rescue Exception => ex # What exception has been caught? assert_equal NoMethodError, ex.class # What message was attached to the exception? # (HINT: replace __ with part of the error message.) assert_match(/undefined method/, ex.message) end end 
+1
source

Source: https://habr.com/ru/post/1347631/


All Articles