in the following code
begin raise StandardError, 'message' #some code that raises a lot of exception rescue StandardError #handle error rescue OtherError #handle error rescue YetAnotherError #handle error end
I want to print a warning stating the type and the message of the error without adding print statement to each of the rescue clauses, like
begin raise StandardError, 'message' #some code that raises a lot of exception rescue StandardError #handle error rescue OtherError #handle error rescue YetAnotherError #handle error ??? print "An error of type #{???} happened, message is #{???}" end
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 ).
In Ruby we have a way to deal with these cases, we have begin, end(default try catch) and we can use try and catch, both try catch and raise rescue used for the same purpose, one will throw exception(throw or raise) with any specific name inside another(catch or rescue).
Exceptions are Ruby's way of dealing with unexpected events. If you've ever made a typo in your code, causing your program to crash with a message like SyntaxError or NoMethodError , then you've seen exceptions in action. When you raise an exception in Ruby, the world stops and your program starts to shut down.
begin raise ArgumentError, "I'm a description" rescue => e puts "An error of type #{e.class} happened, message is #{e.message}" end
Prints: An error of type ArgumentError happened, message is I'm a description
If you want to show the original backtrace and highlighting, you can take advantage of Exception#full_message:
full_message(highlight: bool, order: [:top or :bottom]) → string
Returns formatted string of exception. The returned string is formatted using the same format that Ruby uses when printing an uncaught exceptions to stderr.
If highlight is
true
the default error handler will send the messages to a tty.order must be either of
:top
or:bottom
, and places the error message and the innermost backtrace come at the top or the bottom.The default values of these options depend on
$stderr
and itstty?
at the timing of a call.
begin raise ArgumentError, "I'm a description" rescue StandardError => e puts e.full_message(highlight: true, order: :top) end
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