Ruby

Handling Exceptions

silveryen 2022. 9. 11. 03:55
# handling Exceptions #

num = 0

begin # error 가 뜨는 구간이 지정하고 exception을 만나기까지 실행 > exception에 도달되면 즉시 jump to rescue 된다. 
    puts "dividing 10 by #{num}"
    ans = 10 / num
    puts "the answer is #{ans}"
rescue # error가 떳을 때 대처되는 handling 방식
    puts "There was an error with that division."
end

puts "--------"
puts "finished"
dividing 10 by 0
There was an error with that division.
--------
finished
num = 5

begin 
    puts "dividing 10 by #{num}"
    ans = 10 / num
    puts "the answer is #{ans}"
rescue 
    puts "There was an error with that division."
end

puts "--------"
puts "finished"
dividing 10 by 5
the answer is 2
--------
finished