string conversion of $! - ruby

I am trying to handle an exception caused by this following code:
begin
reader = CSV.open(ARGV[0],col_sep=";")
rescue
puts "exception: " + $!
exit
end
Unfortunately I cannot display correctly the message, Ruby does not interpret $! as string and neither seems to be able to convert it correctly:
$ ruby.exe fixcsv.rb csvfile
fixcsv.rb:11:in `+': can't convert ArgumentError into String (TypeError)
from fixcsv.rb:11:in `rescue in <main>'
from fixcsv.rb:8:in `<main>'
I really cannot understand why this happens; the following tutorial displays similar code that obviously takes into account a correct string conversion of $!:
http://ruby.activeventure.com/programmingruby/book/tut_exceptions.html
Has this anything to do with the fact that I did not explicitly set the exception class?

While I would recommend doing what fl00r did (Exception => e), you can still use $! if you really want to:
begin
reader = CSV.open(ARGV[0],col_sep=";")
rescue
puts "exception: " + $!.message
exit
end

begin
reader = CSV.open(ARGV[0],col_sep=";")
rescue Exception => e
puts "exception: #{e.message}"
end

You don't even need to add .message to e, from #fl00r's example:
begin
reader = CSV.open(ARGV[0],col_sep=";")
rescue Exception => e
puts "exception: #{e}"
end
What happens is that Ruby calls .to_s on the exception e. Exceptions implement to_s, they merely don't implement to_str, which is what "exception: " + $! tried to do.
The difference between to_s and to_str is that the former means "You can change me into a string, but I'm not like a string at all", whereas the latter means "Not only can you change me into a string, but I'm very much like a string". Jorg W Mittag's discussion on to_s versus to_str is well worth reading.

Related

What are the empty single quotes for after rescue?

while t = Integer(gets.chomp) rescue ''
if t.is_a? Integer
break
else
print "Please enter a whole number "
end
end
I'm just trying to figure out exactly why I need those empty single quotes after rescue for this loop to work.
because Integer(gets.chomp) can raise an exception, which caught by rescue and assign to t value as empty string
This is referred to as an inline rescue. If t = Integer(gets.chomp) raises any exception inheriting from StandardError it will be rescued and an empty string will be returned instead. You can think of it like this:
begin
do_something
rescue
''
end
The problem with this approach is that you can't specify exception classes to rescue from, so you may accidentally mask errors that you didn't expect, like a NoMethodError raised when misspelling the chomp method:
Integer(gets.chmp) rescue ''
#=> ""

Ruby Syntax of '=>' (hashrocket)

I tried this earlier and everyone got off on rescue block syntax. Please don't go there. Given the following working code:
begin
(1..1000).each do |i|
puts i
sleep 1
end
rescue Exception => e
puts "\nCaught exception..."
puts "Exception class: #{e.class}"
end
Pressing CTRL+C while it is running prints out "Caught exception...", as expected. What exactly is going on syntax wise in the rescue line, particularly between Exception and the variable e with the => in between?
The word "rescue" is a keyword... part of the ruby language. "e" is a variable, and could just as functionally be "a", "b", or "c". The following code works just as well.
begin
(1..1000).each do |i|
puts i
sleep 1
end
rescue Exception => b
puts "\nCaught exception..."
puts "Exception class: #{b.class}"
end
What are "Exception" and "=>"? Is there another way to write this expression to make it more intelligible from a syntactical point of view? I don't think we're dealing with a hash here because the following code compiles but throws an error as soon as CTRL+C is pressed (undefined local variable or method `e').
begin
(1..1000).each do |i|
puts i
sleep 1
end
rescue { Exception => b }
puts "\nCaught exception..."
puts "Exception class: #{b.class}"
end
Can someone explain what is going on? and specifically what language element '=>' (hashrocket) is in this specific example since it seems to have nothing to do with hashes?
I'm sorry to inform you that this is just one-off syntax that doesn't really have any relation to other Ruby syntax.
Given the expression:
begin
# ...
rescue FooError, BarError => ex
# ...
end
FooError, BarError is the list of exception classes (usually subclasses of StandardError) that will be rescued. This behaves just like an argument list, so you can (if you want) do stuff like this:
my_exception_classes = [ FooError, BarError ]
begin
# ...
rescue *my_exception_classes => ex
# ...
end
It's worth noting that you shouldn't, generally, use Exception here because it will rescue all exceptions, including things like SignalException::Interrupt and NoMemoryError, which usually isn't what you want.
=> is just syntax, and arguably not the best choice of syntax for the reason that it leads to questions like your own.
ex is the name of a local variable into which the exception object will be put.
Digging deeper
If you're into reading parser grammars, it's always fun looking at Ruby's YACC grammar in parse.y. It's not especially easy to read, but we can see the grammar for a rescue expression, called opt_rescue in the grammar, here:
opt_rescue : k_rescue exc_list exc_var then
compstmt
opt_rescue
k_rescue is of course the keyword rescue. exc_list is the list of exception classes which, like I said, is just like an argument list:
exc_list : arg_value
exc_var is the part where the variable to put the exception in is designated:
exc_var : tASSOC lhs
And here, tASSOC is of course our friend the hashrocket (=>), and lhs, i.e. “left-hand side,” is an expression you'd find to the left of an assignment expression (like, say, the name of a variable).
compstmt is basically “any valid Ruby code,” and then there’s opt_rescue again, since you can (optionally) have many rescues in a begin or def block.
As you can see, the only thing this syntax has in common with a Hash is tASSOC.

Why does ruby throw error when calling to_sym against a select-one?

I'm running up against an error when I call to_sym against an element of type "select-one".
begin
["//select", "//input"].each do |t|
puts 'finding input for : ' + t
elements = all(:xpath, t)
elements.each do |e|
puts "found element #{e[:id]} of type #{e[:type]}" if #debug
puts "to symbol result: " + e[:id].to_sym #This line explodes
#...
rescue
puts "failed to enter fields on #{#name}"
raise
end
I get the error "Failed to enter fields on pageName". This error occurs when I call to_sym on Element of type select-one. How can I pinpoint the cause of this error and resolve it?
UPDATE
Per #axeltetzlaff I installed Pry. I noticed the values[salutation] returns nil where I expect a value given below:
[1] pry(#<Step>)> values[e[:salutation]]
=> nil
[2] pry(#<Step>)> values
=> {:z=>"z",
:a=>"a",
:b=>"b",
:c=>"c",
:d=>"d",
:e=>"e",
:f=>"f",
:g=>"",
:h=>"",
:salutation=>"Mr.",#See...I have a value
Update2
I took out the puts I am using for debugging and the issue went away:
puts "to symbol result: " + e[:id].to_sym #This line explodes
The code no longer breaks on the next line. By simple deduction, the issue is that I cannot concatenate a string and a symbol. I am guessing there is some ruby rule somewhere that says I can't do this, but I do not have one available.
to_sym converts a string to a symbol. For example, "a".to_sym becomes :a
Make sure your e[:id] returns a string object on which you are calling to_sym method. Try inspecting:
puts e[:id].inspect
puts e[:id].class
Update:
You can't concat a string and a symbol in Ruby. That will throw no implicit conversion of Symbol into String (TypeError) exception.
Instead of doing:
puts "to symbol result: " + e[:id].to_sym
you could do the same thing using string interpolation like this:
puts "to symbol result: #{e[:id].to_sym}"

multiple assignment in rescue clause?

I ran into this sample code as an idiom for exception handling in Ruby:
begin
eval string
rescue SyntaxError, NameError => boom
print "String doesn't compile: " + boom
rescue StandardError => bang
print "Error running script: " + bang
end
I'm confused particularly about the local variable assignment line with multiple exceptions:
rescue SyntaxError, NameError => boom. Does that mean the local var boom will take on either the SyntaxError or NameError object? Or is it just the NameError that will be assigned?
It's further confusing because the code itself throws a TypeError, I think perhaps because string is undefined, but that may be beside the point.
I found the code above at http://phrogz.net/programmingruby/tut_exceptions.html. Was that your source?
In any event, the local variable in that code is assigned whichever error is raised; it's just specified after the last one.
And yes, it's throwing TypeError because the errors do not implicitly coerce to a string in today's Ruby. Perhaps they used to when the book was initially published. You need to add .message to the local variable reference to get the error message (e.g. + boom.message).

Ruby Exception.to_s doesn't match expected string

I have a rescue block which checks for the correct exception thrown or not as follows:
rescue Exception
if $!.to_s() != "myException"
Err("Unexpected error :" + $!)
end
else
Err("No error")
My $!.to_s() contains large strings as follows when I puts like:
puts $!.to_s()
Output of above puts before if statement is:
myException \n
th sdfsj dsjhf sdfj \n
asdj jkds fdf j
So in if statement I want to compare the first line from output of $!.to_s() with string in double quotes.
Any suggestions how to resolve this?
That makes my eyes hurt. Please do object-oriented programming in ruby.
class MyException < StandardError; end
will define a new exception you can rescue by
begin
do_something_that_raises_expected_exception
rescue MyException
do_something_else
end
So you won't need any String comparison.
If you want to go down your road, use string.match exception_name, but I advise against it.
Another word on rescuing: Don't do rescue Exception if possible, just use rescue, because Exception captures stuff like SyntaxError too (which is likely not intended). And exceptions are frowned upon for flow control in ruby, as opposed to python.
Although I fully agree with Tass, here is how you can achieve what you want:
if $!.to_s !~ /\AmyException\s*\n/
...
or
if $!.to_s.lines.first != "myException \n"
...
But please: Don't do that.

Resources