Code examples from Peter C.'s Beginning Ruby.
If I execute this code…
class Drawing
def Drawing.give_me_a_circle
Circle.new
end
class Line
end
class Circle
def what_am_i
“This is a circle”
end
end
end
a = Drawing.give_me_a_circle
puts a.what_am_i
a = Drawing::Circle.new
puts a.what_am_i
a = Circle.new
puts a.what_am_i
I see this output…
This is a circle
This is a circle
ch06.rb:50:in `’: uninitialized constant Object::Circle
(NameError)
The output surprises me. I was expecting an error when ruby executed “a
= Circle.new” because the code is trying to instantiate a class within a
class, without the proper access. However, I was expecting a second
error when the compiler tries to execute “puts a.what_am_i”.
Is it normal for the ruby interpreter/compiler to stop execution and
error output on the first error?
I also noticed that correct code will not be executed after that first
error.
Thanks,
Doug
On 04.12.2010 16:10, Doug S. wrote:
class Circle
a = Circle.new
= Circle.new" because the code is trying to instantiate a class within a
class, without the proper access. However, I was expecting a second
error when the compiler tries to execute “puts a.what_am_i”.
Is it normal for the ruby interpreter/compiler to stop execution and
error output on the first error?
I also noticed that correct code will not be executed after that first
error.
That’s the way exception handling works. And this is not particular to
Ruby. As soon as an exception is raised the interpreter hunts the call
stack upwards in search for an appropriate handler (“rescue” clause).
If it does not find any it will simply terminate the executing thread.
If it is the main thread the interpreter will exit.
The general form of exception handling code looks like this
begin
code that may throw
…
rescue ExceptionType1 => e
handle ExceptionType1
rescue ExceptionType2 => e
handle ExceptionType2
rescue => e
handle standard error
else
no exception
ensure
always
end
Any of rescue, else and ensure clauses can be omitted. Note that
inheritance between Exception types is honored and sub class rescue
clauses must occur before superclass rescue clauses to be used.
In your particular example there would be no point in executing the last
“puts” because the assignment did not take place in the line above and
you would see the same output as from the previous one.
Kind regards
robert
Thanks Robert. Is there a file that I might include or require so that
Ruby would issue an error message, but continue with execution?
I read that same tutorial Keep reading. That error is supposed to happen
and
it shows why it does.
On 04.12.2010 17:58, Doug S. wrote:
Thanks Robert. Is there a file that I might include or require so that
Ruby would issue an error message, but continue with execution?
No, you need to explicitly handle the error. I am sure the book will
explain.
Kind regards
robert