What are the empty single quotes for after rescue? - ruby

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 ''
#=> ""

Related

Why does defined input variable return nil after exception occurs?

I've noticed this strange behavior with the begin/rescue block in Ruby, when I define a variable, and an exception occurs and I try to call that variable that the exception occurred on it returns nil.
For example:
begin
print "Enter a number: "
input = Integer(gets.chomp)
sum = input + 5
puts "This is your number plus five: #{sum}"
rescue ArgumentError
puts "#{input}" #This outputs nil
end
Why does the begin/rescue block work like this, and is there a way to print the variable without it returning nil?
I'm not sure this is what you want but I try
input = gets.chomp
begin
number = Integer(input)
puts "your number plus five: #{number + 5}"
rescue ArgumentError
puts "#{input} is not a valid number"
end

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.

Understanding syntax of the statement "rescue ErrorType1, ErrorType2 => ex"

A quick query:
How would a Java programmer will understand the following Ruby statement:
rescue ErrorType1, ErrorType2 => ex
That is, I want to put brackets/parenthesis around it explicitly.
So, is it?
rescue(ErrorType1, {ErrorType2 => ex})
or,
rescue({[ErrorType1, ErrorType2] => ex})
or, something else...
About the syntax:
rescue ErrorType1, ErrorType2 => ex
Please note following:
There is no hash involved
'rescue' is not a method, you can't even write it as rescue(ErrorType1, ErrorType2 => ex)
Ruby places a reference to raised associated exception into the
global variable $!.
In the above form, the 'rescue' takes a special argument where
you give the name of a local variable to receive the matched
exception, which is more readable then using $!.
Now, look at the syntax again...
rescue is a control structure with it's own syntax, it's not a method call, so your 2nd and 3rd code blocks are invalid syntax, you aren't not passing any arguments.
rescue <exception-class1>[, <exception-class2>] => <a variable to assign the exception to>
so when doing rescue TypeError, StandardError => my_exception it will catch any TypeError or StandardError exception that is raised and assign it to the my_exception local variable.
I suggest the recently translated Ruby Hacking Guide (search for "rescue").
Look at the below code :
begin
a=1/0
rescue => e
p e.class
p defined?(e)
end
# >> ZeroDivisionError
# >> "local-variable"
Where e is a local variable to that exception handling block. In Ruby local variables are created using assignment operation,but in case of exception handling,reference to the currently raised exception is assigned to the local variable e using the hash rocket(=>),instead of =. This is as per design. Don't think of that it is a Hash.
In Ruby we use one or more rescue clauses to tell Ruby the types of exceptions we want to handle.If you write a rescue clause with no parameter list, the parameter defaults to StandardError. Each rescue clause can specify multiple exceptions to catch. At the end of each rescue clause you can give Ruby the name of a local variable to receive the matched exception. The parameters to the rescue clause can also be arbitrary expressions (including method calls) that return an Exception class. If we use raise with no parameters, it re-raises the exception.Handling an Exception
Out of three of your codes only valid is rescue ErrorType1, ErrorType2 => ex. Others will give you syntax error.
Hierarchy(partial) :
StandardError
|
IndexError
|
KeyError
You can specify the error class names as arguments to the rescue list,in any order.On runtime ruby will pick up the correct one from the list. Look the code below :
begin
a = {}
a.fetch(:b)
rescue StandardError,KeyError,IndexError => e
p e.class
end
# >> KeyError
begin
a = {}
a.fetch(:b)
rescue KeyError,StandardError,IndexError => e
p e.class
end
# >> KeyError
If you think,you would tell Ruby interpreter on runtime, which one to match first using paren from the argument list,Ruby will not allow you to do so,in return it will throw to you syntax error. Same also for below :
begin
a = {}
a.fetch(:b)
rescue StandardError => e1
p e1.class
rescue IndexError => e2
p e2.class
rescue KeyError => e3
p e3.class
end
# >> KeyError
Note: If we want to catch more exception classes, we can just write them in line. When we want to handle different errors differently, we can specify several rescue clauses.Ruby Hacking Guide

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.

string conversion of $!

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.

Resources