Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Rails 'raise StandardError.new' and 'raise StandardError'

Tags:

ruby

To handle Rails exceptions, I see people do 'raise SomeException.new' or 'raise SomeException', what are the differences?

Say if I have a class

 class UnableToCreateShipments < StandardError; end

Can I do both?

raise UnableToCreateShipments
raise UnableToCreateShipments.new

Or with message

raise UnableToCreateShipments, 'my error message'
raise UnableToCreateShipments.new('my error message')
like image 779
user1883793 Avatar asked Jul 12 '15 23:07

user1883793


People also ask

What is the difference between throw catch and raise rescue?

catch/throw are not the same as raise/rescue. catch/throw allows you to quickly exit blocks back to a point where a catch is defined for a specific symbol, raise rescue is the real exception handling stuff involving the Exception object.

What does raise do in Ruby on Rails?

raise is a keyword in Ruby which allows us to raise any exception if it found, raise will throw an exception and that exception will be caught inside the rescue statement.

Does raising an error stop execution Ruby?

When you raise an exception in Ruby, the world stops and your program starts to shut down. If nothing stops the process, your program will eventually exit with an error message. Here's an example. In the code below, we try to divide by zero.

How do you raise exceptions in Ruby on Rails?

Ruby actually gives you the power to manually raise exceptions yourself by calling Kernel#raise. This allows you to choose what type of exception to raise and even set your own error message. If you do not specify what type of exception to raise, Ruby will default to RuntimeError (a subclass of StandardError ).


1 Answers

You can do both, but Boris Batsov's Ruby Style Guide and RuboCop recommend the simpler version of just passing the exception class rather than creating an instance of it.

like image 68
Andrew Grimm Avatar answered Sep 21 '22 13:09

Andrew Grimm