怎么知道什么例外救援 [英] How to know what exceptions to rescue

查看:150
本文介绍了怎么知道什么例外救援的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个类,它将加载并保存yaml文件中的设置,如果有事情发生,就会显示错误。我必须抓住例外,我必须知道要抓到什么。不能保证会有什么例外;用户可能会按CTRL + C或内存可能会耗尽,但是 YAML.load_file 只能提供有限数量的异常。没有列出任何功能 YAML.load_file 可能会升高的例外。



当我不知道这些例外是什么?



这个问题已经被问到,但没有真正的答案:




解决方案

blockquote>


当我不知道这些例外情况时,我该怎么抓到他们?你抓住他们,我不知道?捕捉异常是没有意义的。吞咽例外是特别糟糕的做法。



我的经验法则是:只捕获我可以恢复的东西(这意味着已经知道他们是什么)。让其他的泡沫起来,使程序崩溃,或者可能被捕获在一个外部范围内(这将会知道如何从这个具体的范围中恢复)。



如何发现目前加载异常类



这个近10年的代码片段今天仍然有效:

  exceptions = [] 
tree = {}
ObjectSpace.each_object(Class)do | cls |
下一个除了cls.ancestors.include?异常
下一个如果exception.include? cls
例外<< cls
cls.ancestors.delete_if {| e | [Object,Kernel] .include? e} .reverse.inject(tree){| memo,cls |备注[cls] || = {}}
end

indent = 0
tree_printer = Proc.new do | t |
t.keys.sort {| c1,c2 | c1.name< => c2.name} .each do | k |
space =(''* indent);空格|| =''
放置空格+ k.to_s
缩进+ = 2; tree_printer.call t [k]; indent - = 2
end
end
tree_printer.call tr​​ee

在rails控制台中运行它,你会看到很多异常类。 :)


I want a class that will load and save settings in yaml file, and displays an error if something happens. I must catch exceptions and I must know what to catch. There is no guarantee what exception will be raised; user might press CTRL+C or memory may run out, but YAML.load_file can raise only a limited number of exceptions. There is nowhere listed what exceptions a function YAML.load_file might raise.

How can I catch only them when I don't know what those exceptions are?

This question has been asked, but there is no real answer:

解决方案

How can I catch only them when I don't know what those exceptions are?

What are you going to do when you catch them, I wonder? It makes little sense to catch exceptions for the sake of catching. Swallowing exceptions is especially bad practice.

My rule of thumb is: catch only those I can recover from (this implies already knowing what they are). Let the rest bubble up and crash the program or possibly be catched in one of outer scopes (which will know how to recover from this concrete one).

How to discover currently loaded exception classes

This almost 10 year old code snippet still works today:

exceptions = []
tree = {}
ObjectSpace.each_object(Class) do |cls|
  next unless cls.ancestors.include? Exception
  next if exceptions.include? cls
  exceptions << cls
  cls.ancestors.delete_if {|e| [Object, Kernel].include? e }.reverse.inject(tree) {|memo,cls| memo[cls] ||= {}}
end

indent = 0
tree_printer = Proc.new do |t|
  t.keys.sort { |c1,c2| c1.name <=> c2.name }.each do |k|
    space = (' ' * indent); space ||= ''
    puts space + k.to_s
    indent += 2; tree_printer.call t[k]; indent -= 2
  end
end
tree_printer.call tree

Run it in the rails console and you'll see a lot of exception classes. :)

这篇关于怎么知道什么例外救援的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆