phemmer
phemmer

Reputation: 8807

Can't rescue YAML.load exception

I'm trying to handle loading invalid YAML data in Ruby, but seem to be unable to rescue exceptions raised by psych.

This is some example code to demonstrate the issue I'm having:

require 'yaml'
begin
    YAML.load('&*%^*')
rescue
    puts "Rescued"
end

And the exception:

# ruby test.rb
/usr/lib64/ruby/1.9.1/psych.rb:203:in `parse': (<unknown>): did not find expected alphabetic or numeric character while scanning an anchor at line 1 column 1 (Psych::SyntaxError)
    from /usr/lib64/ruby/1.9.1/psych.rb:203:in `parse_stream'
    from /usr/lib64/ruby/1.9.1/psych.rb:151:in `parse'
    from /usr/lib64/ruby/1.9.1/psych.rb:127:in `load'
    from test.rb:3:in `<main>'

Upvotes: 2

Views: 4630

Answers (2)

Leo Correa
Leo Correa

Reputation: 19809

The inheritance for SyntaxError is:

SyntaxError < ScriptError < Exception

rescue without parameters only catches StandardError which is a subclass of Exception:

StandardError < Exception

So, if you want to catch the Syntax errors from Yaml.load, you must rescue SyntaxError => e or to catch all errors using rescue Exception => e.

Upvotes: 9

Reck
Reck

Reputation: 8782

See Begin Rescue not catching error. It is possible to rescue Syntax Errors, but not recommended. This is why you need to jump through the extra hoop of typing "rescue SyntaxError".

Upvotes: 6

Related Questions