gpt4 book ai didi

ruby - 如何让Ruby捕获线程中的语法错误

转载 作者:数据小太阳 更新时间:2023-10-29 07:12:50 24 4
gpt4 key购买 nike

我正在尝试使用 ruby​​ 编写一个双线程客户端,一个线程从套接字读取数据并将其打印出来,另一个线程读取本地数据并将其发送到远程服务器。我发现的问题是 Ruby 似乎无法捕获线程内的错误,这是一个示例:

#! /usr/bin/ruby

Thread.new {
loop {
$stdout.puts "hi"
abc.puts ef
sleep 1
}
}


loop {
sleep 1
}

显然,如果我在线程外键入 abc.puts ef,代码将永远不会运行,因为 Ruby 将报告“ undefined variable abc”。但是,如果它在一个线程内,则没有错误报告。我的问题是,如何让 Ruby 捕获这样的错误?或者至少,报告线程中的错误?

最佳答案

使用Thread::abort_on_exception= :

根据 Thread - Exception Handling :

Any thread can raise an exception using the raise instance method, which operates similarly to Kernel#raise.

However, it's important to note that an exception that occurs in any thread except the main thread depends on abort_on_exception. This option is false by default, meaning that any unhandled exception will cause the thread to terminate silently when waited on by either join or value. You can change this default by either abort_on_exception= true or setting $DEBUG to true.

...

Thread::abort_on_exception = true
Thread.new {
loop {
$stdout.puts "hi"
abc.puts ef
sleep 1
}
}


loop {
sleep 1
}

=>

hi
t.rb:5:in `block (2 levels) in <main>': undefined local variable or method `abc' for main:Object (NameError)
from t.rb:3:in `loop'
from t.rb:3:in `block in <main>'

关于ruby - 如何让Ruby捕获线程中的语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18292096/

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