Catch exception from toplevel - ruby

This is probably a very simple question but I can't seem to find the answer for it anywhere. I'm new to Ruby 1.9 and use it to write short scripts.
My question is how do I handle Exceptions at the toplevel in a file? Is it really necessary to wrap the section which might throw an exception in a begin/end clause?
Essentially what I'm trying to do is this:
File.open( "foo" )
rescue Errno::EACCES => e
# Handle exception

Instead of rescuing the exception, in this case you might want to check for the existence before opening the file.
if File.exist?("foo.txt")
File.open("foo.txt")
else
abort("file.txt doesn't exist")
end

File.open is not doing anything magical, essentially it's just File.new with a block wrapped into begin/ensure, which will close the file automatically for you at the end of the block, no matter if the block ended normally, or if some exception occured inside it.
So you should handle exceptions in the case of File.open like in any other parts of your ruby code.
You can let it slide and let exceptions be handled elsewhere (by other handlers in exception handlers chain), or you can be strict and handle them on the spot. This decision has nothing to do with File.open, it has more to do with the nature of your code/app and target audience. For example, if you are writing a script which will only be run by you, it's probably fine to let the exception slide and crash the script with a stack trace, in other cases you'd probably want to be more "professional" and handle it gracefully, in which case you'd have to use begin/rescue at some point.
Here's the code which hopefully would demystify File.open (it's basically just an implementation of RAII idiom in Ruby)
File.open("foo") {|f|
# do something with the opened file
f.read
# once the block has finished, the file will be closed automatically
}
# File.open is essentially:
f = File.new "foo"
begin
yield f
ensure
f.close
end
# So in any case if you'd like to handle any exception that might be raised, just do the usual thing:
begin
File.open("foo") {|f|
# do something with the opened file
f.read
}
rescue
# handle all the exceptions - either coming from open/new or from inner file-handling block
end
begin
f = File.new "foo"
begin
# do something with the opened file
f.read
ensure
f.close
end
rescue
# handle the exceptions, using multiple rescue if needed to catch exact exception types like Errno::EACCES, etc
end

Related

ruby - how can i still do something when there's error (example: NameError)

i manage to do "something"(like deleting files,etc) when exit or exit! is called from Object.
by changing the method exit and exit! inside Object class. (at_exit is too unreliable)
but then the "something" never execute if there's error such as NameError, etc.
is there way so i can make "something" that still execute if there's error.
(any error possible if necessary).
something like at_exit but works with all errors
thanks in advance for assistance. and forgive me if there's already question ask for this.
i do search a lot before asking here. and found nothing.
edit: i don't know where the original author of the code place the method. since the original author load it from dll files in the exe program the author used for launcher. (i can only edit After the original code take place...). so i think i need another approach for this... but i manage to make a workaround for my problem... by putting begin rescue in other places that send data to the original object. i filter the data send and throw my own error before it reach the main program... so i guess this works too.
Borrowing from an answer on a different thread, and definitely along the lines of what Marek commented, this is how you should handle errors in Ruby:
begin
# something which might raise an exception
rescue SomeExceptionClass => some_variable
# code that deals with some exception
rescue SomeOtherException => some_other_variable
# code that deals with some other exception
else
# code that runs only if *no* exception was raised
ensure
# ensure that this code always runs, no matter what
end
Original credit: Begin, Rescue and Ensure in Ruby?

Ruby Exceptions and when they stop things

I am having trouble understanding ruby exceptions and what happens after an exception occurs.
When an exception happens, and I rescue it, do the commands after the exception still get executed, or does it skip them and jump to the rescue? If I want it to do the stuff after the exception what can I do? Thanks!
In the following example:
begin
var = "string"
var.do_someting to raise exception
var.do_something_else
var.do_something_else_again
rescue => e
puts "error was #{e}"
end
It halts and jumps straight to rescue. If there's stuff that must run no matter what, ensure is probably what you want.
Begin, Rescue and Ensure in Ruby?
http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_exceptions.html

How to make script continues to run after 'raise' statement in ruby?

I'm checking to see if there is any error message in a log file. If an error message found in a log file, then I use 'raise' statement to report the founding. However ruby stops running after executed the 'raise' statement, even when I use 'rescue'. I'd like script continue checking next log file for error after the 'raise' statement, but not sure how. Any help would be appreciated!
logs_all = s.sudo "egrep -i '#{error_message}' #{log_file}"
logs_all.each do |hostname, logs|
unless logs.empty?
puts line, "Unhappy logs on #{hostname}", line, logs
happy = false
end
begin
raise "Unhappy logs found! in #{log_file}" unless happy
rescue raise => error
puts error.message
end
end
Your rescue statement doesn't look right:
rescue raise => error
should be:
rescue => error
which is equivalent to:
rescue StandardError => error
If you rescue an exception and don't re-raise it, ruby will continue on. You can easily verify this with something like:
3.times do |i|
begin
raise "Raised from iteration #{i}"
rescue => e
puts e
end
end
You'll see that three lines of output are printed.
As a general practice though, you should avoid rescuing Exceptions unless you're going to do something at runtime to rectify the problem. Rescuing and not re-throwing exceptions can hide problems in your code.
And more generally, please follow Sergio's advice above and don't use exceptions as control flow.
Further Reading
I recommend looking over the Exceptions section of this ruby style guide - it will give you some quick pointers in the right directions.
Also, this answer about never rescuing Exception
You are using exceptions as control flow mechanism. Don't.
What is it that you want to do with unhappy logs? Print them? To a file, maybe? Do that, don't raise exceptions.

Ruby Exceptions in a loop

I have a ruby script that loops through a list of shortened urls (around 2,000 - 3,000 at a time). At the moment everything is peachy until a hit a url that is malformed, timedout etc. When an error occurs my script dies. How can I setup my loop to skip to the next record when/if such an error occurs.
my loop looks like this:
blah.foo do |barurl|
mymethod(barurl)
my mymethod looks like this:
def mymethod(barurl)
begin
stuff
...
return expandedurl
rescue
return "Problem expanding link"
end
end
Should my begin/end logic be wrapped around my loop instead of the method?
Because you need to skip the malformed url, you should use the exception message to control the loop
blah.foo do |barurl|
begin
mymethod(barurl)
rescue YourTypeOfException
next
end
end
and inside the method raise the exception
def mymethod(barurl)
stuff
...
raise YourTypeOfException, "this url is not valid"
...
end
I found the existing answers unsatisfying, and reading the documentation suggests to me that the OP had something more like the example suggested there in mind:
[0, 1, 2].map do |i|
10 / i
rescue ZeroDivisionError
nil
end
#=> [nil, 10, 5]
The docs specifically note that a rescue block permits the loop to continue on a caught exception (as indicated by the example).
Yes. All your method does is consume the exception and return another arbitrary object in order to indicate an error.
Your method shouldn't handle its own exceptional conditions. It is just rude on its part to make assumptions about how the caller will react.
blah.foo do |url|
begin
my_method url
rescue
next
end
end
Whether to skip to the next URL or print a message is not a decision the method should be making. Its only concern should be working with the URL.
With that said, you should simply let it propagate and only rescue from it when you can actually deal with it. Don't rescue from a TimeoutError if all you can do is return :timeout.
Do rescue when you need to clean up resources or simply let the user know an error occurred.
Also, rescuing from every possible error just to make them go away is a nice way to introduce bugs. Be as specific as possible.
having exception handling within your method is proper way of doing it, so your implementation is fine
i can only point some ruby sytax sugar to you:
def some_method
# here goes the code
rescue Exception => e
# here goes specific exception/error handling
rescue
# here goes error handling (not Exception handling though!)
else
# do this block when no exceptions are raised
ensure
# do this every time
end
btw you don't need return statements, last value of code block is always returned implicitly
ah i guess i misread your question in the "how to skip next record"
if you want to skip the record after current one that was incorrect you would have to return error code from your parsing method and set up skipping within your loop using break or next keywords
It should be inside the loop, so the loop structure isn't exited on an exception. But it looks like it already is--if you're rescuing inside the method that causes the exception, the loop should already continue normally, because it shouldn't be seeing the exception.

How to use Dir.mktmpdir with a block in a hook with rspec?

I want to create a tmpdir in a before-each hook and use its path in an rspec example. I want to use the block form of Dir.mktmpdir so the dir is removed at the end of the example.
Problems:
I can't let the block exit in the before hook, or the dir is removed before my example can run.
I can't wrap a block around my example. I tried using an around
hook, but that doesn't share instance variables with examples (the
doc confirms this behavior).
Currently I'm using continuations (Fibers would be better if I were on 1.9) to jump out of the block, then jump back in so mktmpdir can clean up.
Is there an easier way to accomplish this, without moving mktmpdir inside each example? It's true that I can remove the dir in the after-hook, but I'm also looking for a general solution to this type of problem - I don't always know what cleanup code is supposed to run when the block exits.
FYI, my continuation code, encapsulated into a class:
class SuspendableBlock
def initialize
end
def run(&block)
raise LocalJumpError unless block_given?
callcc {|#run_cc|
yield
#resume_cc.call if #resume_cc
}
nil
end
# saves the suspend point & causes run to return immediately
def suspend
raise "run must be called first" unless #run_cc
callcc {|#suspend_cc|
#run_cc.call(#suspend_cc)
}
nil
end
# jumps back to after the suspend point to finish the block.
# after the block exits, return immediately from resume.
def resume
raise "suspend must be called first" unless #suspend_cc
callcc {|#resume_cc|
#suspend_cc.call(#resume_cc)
}
nil
end
end
Usage:
before :each do
#sb = SuspendableBlock.new
#sb.run do
Dir.mktmpdir do |dir|
#tmpdir_path = Pathname.new(dir)
#sb.suspend
end
end
end
after :each do
#sb.resume
end
it "should use a tmp dir" do
p #tmpdir_path
end
From what I read (never tested it) continuations are really inefficient.
While I cannot help you on continuations you could use Thread to mimic Fibers: https://github.com/tmm1/fiber18.
One library which already does that is em-spec (https://github.com/tmm1/em-spec), with it each test is ran in a fiber you may be able to modify it to match your needs.

Resources