In job change activities, I sometimes described exception handling in technical issues, but I have never experienced it before, so it is an output
begin
#Specify code to detect problems when running a program
#Write code that is likely to cause an error
rescue
#Describe how to respond when a problem is detected
end
With the following code, 100 / 0
cannot be executed, so processing will stop at ʻanswer = 100 / number.
ZeroDivisionError` is the corresponding error, and describe the processing you want to perform when this exception occurs.
number = 0
answer = 20 / num
puts answer
puts 2
=>`/': divided by 0 (ZeroDivisionError)
from Main.rb:4:in `<main>'
If you write as follows, the exception will normally occur at 100/0
, so the processing will stop, but since the processing in rescue is performed, the processing will be executed to the end.
puts 1
begin
#Write the code you want to detect
number = 0
answer = 20 / num
puts answer
rescue ZeroDivisionError => e
#Describe the process you want to perform when ZeroDivisionError occurs (register an exception handler)
p e
ensure
puts 2
end
=>
1
#<ZeroDivisionError: divided by 0>
2
It is a ZeroDivisionError object (variable) that stores the details of the exception that occurred. In other words, if you output this, you can understand why the error occurred.
Objects have various messages and can retrieve necessary information as shown below.
p e
puts e.message
p e.backtrace
=>
#<ZeroDivisionError: divided by 0>
divided by 0
["Main.rb:4:in `/'", "Main.rb:4:in `<main>'"]
Recommended Posts