Ruby - Exceptions (rescue, raise) 2020
bogotobogo.com site search:
rescue
In this article, we'll learn how to try/catch (begin/rescue):
#!/usr/bin/ruby # f1.rb # How to function def addition(n1, n2) return n1.to_i + n2.to_i end puts addition(3,9)
Output 1 :
$ ./rescue.rb Enter a number : 10 Enter another number : 2 10/2 = 5
Output 2 :
$ ./rescue.rb Enter a number : 9 Enter another number : 0 Division by zero! ./rescue.rb:16:in `/': divided by 0 (ZeroDivisionError) from ./rescue.rb:16:in `<main>'
raise
Now, we may want to raise:
#!/usr/bin/ruby # raise.rb # How to try/catch (begin/rescue/raise) weight = 150 def check_weight(w) raise ArgumentError, " Enter positive number" unless w > 0 end begin check_weight(-1) rescue ArgumentError puts "Weight should be greater than 0" end
Output:
$ ./raise.rb Weight should be greater than 0
Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization