Can't rescue YAML.load exception

ε祈祈猫儿з 提交于 2019-12-10 23:07:16

问题


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>'

回答1:


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".




回答2:


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.



来源:https://stackoverflow.com/questions/14676656/cant-rescue-yaml-load-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!