Untrapped Error
-
I'm writing a console. You input
2+2and 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 linesI'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
rescuestatement? 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 => eto catch everything.
-
@unknownuser said:
rescue Exception => eto 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.)
Hello! It looks like you're interested in this conversation, but you don't have an account yet.
Getting fed up of having to scroll through the same posts each visit? When you register for an account, you'll always come back to exactly where you were before, and choose to be notified of new replies (either via email, or push notification). You'll also be able to save bookmarks and upvote posts to show your appreciation to other community members.
With your input, this post could be even better π
Register LoginAdvertisement