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')
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.
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.
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.
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 ).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With