Ruby Exception Handling Issues

I was looking at a Ruby programming book, and I am having trouble understanding the following concepts:

  • The authors talk about β€œtemporary exceptions” that may occur in code, and then propose creating their own exception object to handle them. I do not think that I fully understand what a temporary error is, and when it is appropriate to create your own Exception object. He talks about this in Chapter 6 when he talks about defining exceptions:

For example, some types of network errors may be temporary. Chapter 6. Part 97. Adding information to exceptions.

  1. It's also not easy for me to get around using Catch and Throw in ruby. When is it better than raising and saving?
+3
source share
1 answer

Can you provide a link to the transitional exceptions page?

In any case, you can create a new exception at any time, and it's usually good to do so that you can pass additional information about the failure. This is especially good when you have an allow level exception and want to make it more meaningful to the user.

Throw / Catch in Ruby is indeed a kind of non-local transition, such as setjmp / longjmp in C, but it's better to behave. You will use it anytime you want to broadcast execution in long ways.

, goto, . , , - , , , , , , .


, , . 97 , , .... , , . 157 .

, " " , , , , BOFH . , , , . ?

. :

class RetryException < RuntimeError
  # so this is a kind of RuntimeError which is a kind of Exception
  attr: ok_to_retry
  def initialize(ok_to_retry)
     @ok_to_retry
  end
end

, - ,

raise RetryException.new(true), "transient read error"

- RuntimeError , , , , ", ".

NOw, Ruby: . , - , :

begin
   # do something that raises this exception
   do_something()
rescue RetryException => detail 
   # if the exception is one of these retryable ones, 
   # catch it here, but it in detail
   if detail.ok_to_retry  
      retry
   end
   # this means exactly the same as 'retry if detail.ok_to_retry`
   # from the book, btw

   # if it STILL doesn't work, send the exception on
   raise # just re-raises the last exception
end
+11

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


All Articles