This article is a supplement to a number of exception handling. Specifically, I will leave the result of verifying the pattern not introduced in the article.
In the function, you can write as follows.
def method
  puts "hoge"
  a = 1 / 0
rescue ZeroDivisionError
  puts $!
end
It is a form that omits begin and end. In the case of such a shape
a = 1 / 0
Is obvious that will cause an error. But what if:
def method
  #Huge processing 1
  #Processing that is likely to cause an error
  #Huge processing 2
rescue StandardError
  puts $!
end
By the way, it is doubtful that the person who sees this code can immediately see the processing that is likely to cause an error. In that case, I think you should dare to write begin and end.
def method
  #Huge processing 1
  begin
    #Processing that is likely to cause an error
  rescue StandardError
    puts $!
  end
  #Huge processing 2
end
This way you can see where the error is likely to occur and you don't have to scroll a lot to see the rescue. By the way, if you return with rescue, the huge amount of process 2 will not be processed, so if you definitely want it to be processed, put it in ensure.
def method
  #Huge processing 1
  begin
    #Processing that is likely to cause an error
  rescue StandardError
    puts $!
    return
  ensure
    #Huge processing 2(Even if there is a return in rescue, it will be processed)
  end
end
If there are multiple processes that are likely to cause an error, I think it is simple to write them together at the end of the function. Writing begin, rescue, end every time will make it less readable. Everything is right.
def method
  #Processing that is likely to cause various errors
  #Other processing
rescue ZeroDivisionError, ArgumentError
  puts $!
rescue StandardError
  puts $!
  puts $@
end
By the way, if you write StandardError first, this guy will do most of the error handling. So let's start with the child class.
Recommended Posts