gpt4 book ai didi

ruby - Ruby Kernel方法的错误处理不起作用

转载 作者:行者123 更新时间:2023-12-03 08:28:34 25 4
gpt4 key购买 nike

我发现自己需要执行一个字符串。当前方法是使用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

关于ruby - Ruby Kernel方法的错误处理不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33502986/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com