exception handling in ruby

>begin expression executes its body and returns the value of the last evaluated expression.
>Any error in begin part will be caught by rescue depending upon parameters
>ensure is the one which must be exectued irrespective of exception occured or not
>An error message caught by an exception can be accessed using $!

For Java Programmers [ begin => try ; rescue => catch; ensure => finally]

begin
p “I am doing well”
p “so well .. and well”
a = 8/0
rescue
p “Something went wrong => ” + $!
ensure
p “Oh Somehow I could finish my work”
end

O/P:

“I am doing well”
“so well .. and well”
“Something went wrong => divided by 0?
“Oh Somehow I could finish my work”

a = 8
b = 0
begin
p “I am doing well”
p “so well .. and well”
if a==18
p “I am happy with a as 8”
elsif b == 0
p “Lets say I dont want this”
raise Exception
else
raise
end

rescue
p “Exception 1 caught here ” + $!
rescue Exception
p “Exception 2 caught here ” +$!
ensure
p “Oh Somehow I could finish my work”
end

O/P for [[ a = 8 and b = 0 ]]
“I am doing well”
“so well .. and well”
“Lets say I dont want this”
“Exception 2 caught here Exception”
“Oh Somehow I could finish my work”

O/P for [[ a = 8 and b = 1 ]]
“I am doing well”
“so well .. and well”
“Exception 1 caught here “
“Oh Somehow I could finish my work”

Be Sociable, Share!