Untrapped Error
-
I'm writing a console. You input
2+2
and it outputs2+2 # 4
. Problem is, your input may not be perfect, so a little error trapping is needed.In this part of the
process()
function (line #s added):59 results = [] 60 for line in lines do 61 rslt = line.chomp() + ' # ' 62 begin 63 rslt += eval(line).to_s().chomp() 64 rescue => e 65 rslt += e.to_s().chomp() 66 end 67 68 results.push( qq(rslt) ) 69 end # loop over lines
I'm thinking that an error at line 63 gets caught and reported at line 65. It usually does. Now, however, I've got this:
Any ideas why this isn't caught by the
rescue
statement? Any ideas on how to catch it? -
From the Pickaxe Book: (Ruby 1.8, page 110)
@unknownuser said:
"If you write a rescue clause with no clause parameter list, the parameter defaults to StandardError"
You got a SyntaxError, which is part of ScriptError, not StandardError.
Try this:
rescue Exception => e
to catch everything.
-
@unknownuser said:
rescue Exception => e
to catch everything.
I don't want to seem ungrateful, but that upgraded me to Bug Splat. Is there a
rescue BugSplat => e
???
-
Do you have access to the pickaxe book? Try ScriptError. Try a stepladder of all the exception subclasses with multiple rescues.
-
@martinrinehart said:
> 64 rescue => e > 65 rslt += e.to_s().chomp() > 66 end >
Your local reference e receives a pointer to an Exception object from the rescue clause, not a String object.
You should use the instance method Exception.message to get the exception's string, like this:
65 rslt << e.message.chomp()
(As a side-note on Optimization, generally speaking, + and += String concatenation, require Ruby to create at least one extra String object than String append <<. Ruby internally converts a+=b to a=a+b, OR a+='literal' to a=a+'literal', so using += doesn't gain you anything over <<, and may be twice as slow or more, in a loop.)
Advertisement