Exception handling is to handle when an error occurs. It is convenient to write exception handling to identify the cause of the error and prevent problems on the system side.
Enclose the part that is likely to be the target of the error with begin, and write the processing when the error occurs in rescue.
begin
100 / 0
rescue
p "Does not break at 0"
end
puts "Good morning"
It is also possible to write with one liner.
sample_1 = 10 / 0 rescue 0
sample_2 = 10 / nil rescue 0
puts sample_1 #=>0
puts sample_2 #=>0
You can also specify an argument after rescue to store the error content in a variable.
begin
10 / 0
rescue => e
puts e #=> divided by 0
end
Alternatively, by specifying an error message after rescue, You can make a conditional branch to decide which error to take and what to do.
begin
10 / 0
rescue NoMethodError
puts "There is no method"
rescue ZeroDivisionError
puts "Does not break at 0"
end
It is used when you want to explicitly generate an error and interrupt the process when the parameters are not expected or when an unauthorized access occurs.
begin
raise NoMethodError #The class of exception you want to raise
rescue => e
puts e
end
It is also possible to output an error message.
begin
raise RuntimeError, "Run-time error"
rescue => e
puts e
end
If you get an error, you can go back to begin and run it again.
num = 0
begin
puts 10 / num
rescue ZeroDivisionError => e
puts e
num = 1
retry #Run the begin block again
end
puts "Finished"
You can write a process that will be executed with or without an exception.
begin
puts "No exception"
rescue => e
puts e
ensure
puts "Absolutely run here!"
end
Recommended Posts