0

The following function might return a null value hence I want to use the exception flow. Can someone direct me to the correct way to do it because right now I am getting the error.

syntax error, unexpected keyword_else, expecting keyword_end else

def value_from_table1(field, key)
    begin 
      @@connection.query("SELECT #{field} FROM table1 Where key = #{key}  ").each do |row|
        rescue Exception=>e
          puts e
        else 
          return row[field]
        end
    end
end
vgoff
  • 10,980
  • 3
  • 38
  • 56
Raj
  • 11
  • 1
  • 5
  • You should escape your query parameters. – Justin Turner Jul 28 '15 at 20:23
  • 1
    If you take the error flow you should wrap the `row[field]` expression. See e.g. http://phrogz.net/programmingruby/tut_exceptions.html – sschmeck Jul 28 '15 at 20:31
  • why not just make sure to return an enumerable object (that is an object that responds to each) then there is no concern. Also right now if there are multiple rows you will only get the first one which seems wrong too but I am not sure what you are attempting to do. – engineersmnky Jul 28 '15 at 21:01

2 Answers2

0

You are passing a block to Enumerator#each which introduces a new scope, so you need to put begin as a start of exception block inside.

If you also need handle exceptions of @@connection.query, just put rescue after do-end block of .each. begin is implicit at start of method's body.

joanbm
  • 793
  • 1
  • 6
  • 13
0

First, rescuing from Exception is always a bad idea, see Why is it a bad style to `rescue Exception => e` in Ruby? for details.

Second a begin rescue block always has to have a closing end, else is only possible after an if before

begin
  # ...
rescue StandardError => e 
  # ...
end

Third as already said by Justin Turner in the comment, just passing a value to the DB like that makes it prone to SQL injections. Is there any reason you don't use ActiveRecord but want direct DB access?

Overall there are so many issues with this short piece of code, I would suggest to read http://guides.rubyonrails.org/ to better understand what is going on.

Community
  • 1
  • 1
Bruno E.
  • 1,284
  • 11
  • 16