Does Crystal's exception handling follow a different logic from Ruby's?

begin
    a = 1/0
rescue 
    puts "Do not divide by zero"
    a = :bad_result
end

puts "After exception handling"
puts a

Ruby:

After exception handling
bad_result

Crystal:

After exception handling
Infinity

No, exception handling is the same. What’s different is that division by default is float division. It never raises.

3 Likes

I see.Thanks!

This snippet is a better example:

begin
    File.open("Googoo.txt")
rescue e 
    puts e
    puts "Error occured in fle: #{__FILE__} on line #{__LINE__}"
end

The equivalent Crystal code from your original example would be:

begin
    a = 1//0
rescue 
    puts "Do not divide by zero"
    a = :bad_result
end

puts "After exception handling"
puts a

Here’s the output.

2 Likes