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")
精彩评论