Pat*_*ick 2 ruby yaml exception-handling exception
我正在尝试处理在Ruby中加载无效的YAML数据,但似乎无法挽救心理引发的异常.
这是一些示例代码,用于演示我遇到的问题:
require 'yaml'
begin
YAML.load('&*%^*')
rescue
puts "Rescued"
end
Run Code Online (Sandbox Code Playgroud)
例外情况:
# 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>'
Run Code Online (Sandbox Code Playgroud)
继承SyntaxError是:
SyntaxError < ScriptError < Exception
Run Code Online (Sandbox Code Playgroud)
rescue没有参数只捕获StandardError哪个是以下的子类Exception:
StandardError < Exception
Run Code Online (Sandbox Code Playgroud)
因此,如果要捕获语法错误Yaml.load,则必须rescue SyntaxError => e或使用捕获所有错误rescue Exception => e.