Ruby |线程中的异常处理|集–1

线程也可以包含异常。在Ruby线程中,只处理主线程中出现的异常,但如果线程中出现异常(主线程除外),则会导致线程终止。在主线程以外的线程中出现异常取决于 异常方法上的中止 这个 异常时中止_的默认值为false。 当异常上的abort_值为false时,表示未处理的异常将中止当前线程,其余线程将继续运行。 您还可以使用 bort_on_exception=true或$DEBUG to true .Ruby线程还提供了一种处理异常的方法,即。 ::处理中断 。此方法将异步处理异常。

null

例子:

# Ruby program to illustrate
# the exception in thread
#!/usr/bin/ruby
threads = []
4 .times do |value|
threads << Thread . new (value) do |a|
# raising an error when a become 2
raise "oops error!" if a == 2
print "#{a}"
end
end
threads. each {|b| b.join }


输出:

0
3
1
main.rb:12:in `block (2 levels) in 
': oops error! (RuntimeError)

注: 线参加 方法用于等待特定线程的完成。因为当Ruby程序终止时,所有线程都会被终止,而不管它们的状态如何。我们还可以保存异常,如下例所示:

例子:

# Ruby program to illustrate hwo to
# escape the exception
#!/usr/bin/ruby
threads = []
5 .times do |value|
threads << Thread . new (value) do |a|
raise "oops error!" if a == 3
print "#{a}"
end
end
threads. each do |x|
begin
x.join
# using rescue method
rescue RuntimeError => y
puts "Failed:: #{y.message}"
end
end


输出:

0
1
4
2
Failed:: oops error!

现在 在异常上设置abort_的值=true ,它将终止包含异常的线程。一旦线程失效,就不会产生更多的输出。

例子:

# Ruby program to illustrate the killing
# of thread in which exception raised
#!/usr/bin/ruby
# setting the value of abort_on_exception
Thread .abort_on_exception = true
threads = []
5 .times do |value|
threads << Thread . new (value) do |a|
raise "oops error!" if a == 3
print "#{a}"
end
end
# using Thread.Join Method
threads. each {|b| b.join }


输出:

0
1
2
main.rb:13:in `block (2 levels) in 
': oops error! (RuntimeError)

线程(主线程除外)的执行如下所示:

图片[1]-Ruby |线程中的异常处理|集–1-yiteyi-C++库

© 版权声明
THE END
喜欢就支持一下吧
点赞9 分享