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).
Related
I ran this code:
begin
print 'Enter something:'
x = gets.to_i # Enter a string
rescue => err
print(err.to_s)
end
I don't get why the rescue block does not catch the exception. It always
returns zero when a string is input, and doesn't trigger the rescue block. I don't know why it isn't working. Can anyone please help?
Behavior Differs Between String#to_i and Kernel#Integer
The reason your exception handler is never called is because String#to_i doesn't raise an exception, even if it can't detect a valid integer within the String object. In such cases, it simply returns 0.
In comparison, the behavior of Kernel#Integer is more complex, but is expected to raise ArgumentError or TypeError if the contents of the string do not strictly conform to a numeric representation.
So, to minimally refactor your existing code to raise an exception on non-numeric inputs:
begin
print 'Enter something: '
x = Integer gets
rescue => err
# Do something other than just print err on STDERR, which is the
# default behavior anyway. Perhaps send it to STDOUT instead.
puts "I received an exception: #{err}"
# After handling, re-raise the original exception with or without
# passing the original exception object. `raise` and `raise err`
# will do the same thing here.
raise
# For more advanced uses, you can also do something else like raise
# a different exception (e.g. TypeError), or modify the exception
# object stored in err and raise that modified object instead.
end
The following user inputs will each convert cleanly:
1
2
0xff
The code will even handle initial/trailing spaces, newlines, and carriage returns in most cases, without any additional effort on your part. However:
Enter something: one
ArgumentError: invalid value for Integer(): "one\n"
Enter something: "1"
ArgumentError: invalid value for Integer(): "\"1\"\n"
Enter something: nil
ArgumentError: invalid value for Integer(): "nil\n"
In general, you can rely on Kernel#Integer to raise an exception when necessary, which simplifies your code a lot. However, see caveats below.
Caveats
These examples don't require it, but you might also want to sanitize your input with #strip, #chomp, or other string transformations when necessary. Your mileage in this regard will vary greatly with your real-world use case, but while Kernel#Integer generally does the right thing, and Ruby encourages relying on exceptions to handle non-standard edge cases, it's often unwise to trust user-tainted inputs.
It's also worth noting that both String#to_i and Kernel#Integer might operate on values other than user input, in which case know that Integer(nil) will raise:
Integer nil
TypeError: can't convert nil into Integer
This might be important. Again, your mileage may vary.
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.
The code below defines a hook Kernel#at_exit to capture an exception and do things at exit, and then raises a Sass::SyntaxError by passing an invalid SASS string.
require "sass"
module Kernel
at_exit do
puts "--Before backtrace"
p $!
$!.backtrace
puts "--After backtrace"
p $!
end
end
Sass::Engine.new("Invalid {sass").render
The output it gives is as below:
...
--Before backtrace
#<Sass::SyntaxError: ...>
--After backtrace
nil
...
It indicates that $! was a Sass::SyntaxError, but it became nil right after backtrace has been called on it. Why did $! change just by calling backtrace on it?
This effect does not seem to happen when Sass::SyntaxError is raised manually as follows:
raise Sass::SyntaxError.new("foo")
or when a different type of error is raised (may be wrong).
Edit
I am not sure, but probably sass manipulates the backtrace using set_backtrace when a sass error is raised. This is to provide information about where the sass syntax error was caused in a sass file. And the different behaviour between manually raising an error and programatically raising an error is reminiscent of a bug in Ruby 2.1 that half-way implemented backtrace_locations, but returned nil in some cases. I have a broad guess that these factors are interfering, but am not sure.
The reason it is happening is because this method overrides backtrace method:
def backtrace
return nil if super.nil?
return super if sass_backtrace.all? {|h| h.empty?}
sass_backtrace.map do |h|
"#{h[:filename] || "(sass)"}:#{h[:line]}" +
(h[:mixin] ? ":in `#{h[:mixin]}'" : "")
end + super
end
Where sass_backtrace is an array of hashes populated in initializer. Line which causes $! to be nil is:
return super if sass_backtrace.all? {|h| h.empty?}
This happens only when all? returns nil. I did some fiddling with it, and I found out that the problem always occurs, when we call any iterator which doesn't finish the whole iteration (all? terminates iteration when encounter the first not satisfying element). The problem might be simply reproduced with:
at_exit do
p $! #=> #<RuntimeError: hello>
[<any_non_empty_array>].all? {false}
# Those would break $! as well
# [<ANA>].any? {true}
# [1,2,3].find {|n| n.even?}
# Those will not break $!
# [<ANA>].any? {false}
# [<ANA>].all? {true}
# [1,2,3].find {|n| n > 4}
p $! #=> nil
end
raise 'hello'
The only reason I can think of why it would work like that is that ruby loops are controlled internally with exceptions. When iteration is to be stopped, it is done with special type of exception being raised and rescued outside the loop.
My guess is that Ruby creators didn't want this control exception to be visible in $! variable, since this would suggest that something went wrong, and decided to set it back to nil.
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
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.