Why is it bad style to `rescue Exception => e` in Ruby?

Exception is the root of Ruby’s exception hierarchy, so when you rescue Exception you rescue from everything, including subclasses such as SyntaxError, LoadError, and Interrupt.

Rescuing Interrupt prevents the user from using CTRLC to exit the program.
Continue reading

Advertisements

Ruby On Rails : Exception Handling Best practices

There are various ways to rescue from exceptions raised in Rails App.

The most basic is

begin
.........
rescue NameOfException => exc
   logger.error("Message for the log file #{exc.message}")
   flash[:notice] = "Store error message"
   redirect_to(:action => 'index')
end

Or you can render a static HTML file namely public/401.html or public/400.html.erb
Continue reading

Ruby : Not throwing exception even when divided by Zero : Only when operands are floating points

# Throws an Exception when both operands are integers
# However, if operand are floating point numbers then that is not the case
begin
 puts 'Enter the Number'
 quotient = gets.to_i
 puts 'enter the divider'
 divider = gets.to_i
 result = quotient/divider
 puts "The result is #{result}"
rescue ZeroDivisionError
 puts 'Cannot divide by zero'
 retry
end
# Output
Enter the Number
12
enter the divider
0
Cannot divide by zero
# Whole process within begin block retried
Enter the Number
# However
begin
 puts 'Enter the Number'
 quotient = gets.to_f
 puts 'enter the divider'
 divider = gets.to_f
 result = quotient/divider
 puts "The result is #{result}"
rescue ZeroDivisionError
 puts 'Cannot divide by zero'
 retry
end
# Output
Enter the Number
12
enter the divider
0
The result is Infinity

12.12/0.0
=> Infinity

# However
12/0
ZeroDivisionError: divided by 0

Rails Session value not set problem

I waisted my couple of hours to this problem and I don’t want you to do same.

Problem

# I set session in one controller but when I tried to render from another 
# controller I got nil

def bid_details
 alert_id = params[:id]
 alert = @user.alerts.find(alert_id)
 raise ActiveRecord::RecordNotFound if alert.inactive?
 session[:bid_details] = alert.bid_id
rescue ActiveRecord::RecordNotFound => e
 logger.error e.message
 render '/public/404.html', status: 404 and return false
end

Solution : What had happened is, previously there was no view template assigned to the controller, Rails resets the session when exception occurs. When I rendered something then only my app was able to set session from that controller’s action.

def bid_details
 alert_id = params[:id]
 alert = @user.alerts.find(alert_id)
 raise ActiveRecord::RecordNotFound if alert.inactive?
 session[:bid_details] = alert.bid_id
 # Rendering a view helped me get out of that pit
 render text: 'hello'
rescue ActiveRecord::RecordNotFound => e
 logger.error e.message
 render '/public/404.html', status: 404 and return false
end

sd

Exception handling in Rails

The execution and the exception always go together. If you are opening a file which does not exist then if you did not handle this situation properly then your program is considered to be of bad quality.

The program stops if an exception occurs. So exceptions are used to handle various type of errors which may occur during a program execution and take appropriate action instead of halting program completely.

Exception handling in Ruby on Rails is similar to exception handling in Ruby. Which means, we enclose the code that could raise an exception in a begin/end block and use rescue clauses to tell Ruby the types of exceptions we want to handle