开发者

Can an exception be overwritten?

I have a line like:

@hsh.has_key?(foo开发者_Go百科) ? @hsh[foo][bar] : raise("custom error")

That I'd rather write like:

@hsh[foo][bar] || raise ("custom error")

But the NoMethodError is called instead when @hsh[foo] does not exist.


To save an exception, you need rescue, but you don't have that anywhere in your code. || just reacts to nil.

You might want this:

@hsh.fetch(foo, {})[bar] || raise("custom error")


I think this is the simplest change:

@hsh[foo][bar] rescue raise ("custom error")


It's preferred to avoid triggering exceptions if at all possible, but you can always create an inline block that you can rescue out of:

begin
  @hsh[foo][bar]
rescue
  raise ("custom error")
end


@hsh[foo] returns nil, which doesn't have a [] method. Try this one:

@hsh[foo] && @hsh[foo][bar] || raise("custom error")
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜