Ruby 内核方法无效的错误处理
Error handling for Ruby Kernel method not working
我发现自己需要执行一个字符串。当前的方法是使用Kernel#eval()
方法。一切正常,但我的错误处理不起作用。例如,缺少右引号将完全杀死并退出程序。
这是一段摘录。知道为什么我无法捕捉到错误吗?
def process(str)
print "\n"
eval(str)
rescue => e
puts e
end
>> process('"')
console.rb:90:in `eval': (eval):1: unterminated string meets end of file (SyntaxError)
from console.rb:90:in `process'
from console.rb:81:in `bouncer'
from console.rb:14:in `block in prompt'
from console.rb:11:in `loop'
from console.rb:11:in `prompt'
from console.rb:97:in `<main>'
根据 documentation:
A rescue clause without an explicit Exception class will rescue all StandardErrors (and only those).
SyntaxError
不是 StandardError
。要捕捉它,你必须明确,例如:
def process(str)
print "\n"
eval(str)
rescue Exception => e
puts e
end
process('"')
输出:
(eval):1: unterminated string meets end of file
我发现自己需要执行一个字符串。当前的方法是使用Kernel#eval()
方法。一切正常,但我的错误处理不起作用。例如,缺少右引号将完全杀死并退出程序。
这是一段摘录。知道为什么我无法捕捉到错误吗?
def process(str)
print "\n"
eval(str)
rescue => e
puts e
end
>> process('"')
console.rb:90:in `eval': (eval):1: unterminated string meets end of file (SyntaxError)
from console.rb:90:in `process'
from console.rb:81:in `bouncer'
from console.rb:14:in `block in prompt'
from console.rb:11:in `loop'
from console.rb:11:in `prompt'
from console.rb:97:in `<main>'
根据 documentation:
A rescue clause without an explicit Exception class will rescue all StandardErrors (and only those).
SyntaxError
不是 StandardError
。要捕捉它,你必须明确,例如:
def process(str)
print "\n"
eval(str)
rescue Exception => e
puts e
end
process('"')
输出:
(eval):1: unterminated string meets end of file