Ruby has a fatal
exception, but there is no guidance on how to raise
it and I cannot figure it out. How do I raise a fatal
exception in Ruby?
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 ).
Ruby also provides a separate class for an exception that is known as an Exception class which contains different types of methods. The code in which an exception is raised, is enclosed between the begin/end block, so you can use a rescue clause to handle this type of exception.
Ruby Internal try catch (raise and rescue) In case exceptions happen in the begin block it will halt and control will go between rescue and end, and we can return a valid message for the user in case of exceptions. Every time for a rescue statement Ruby checks and compares the exception raised for each parameter.
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. Syntax: Web development, programming languages, Software testing & others. Below is the simple syntax for the raise statement in Ruby.
Sure you can.
Try this
FatalError = ObjectSpace.each_object(Class).find { |klass| klass < Exception && klass.inspect == 'fatal' }
And then
raise FatalError.new("famous last words")
How does this work?
fatal
is an internal class without associated top-level constantObjectSpace.each_object(Class)
enumerates over all classes find { ... }
finds an exception class named "fatal"NB though, despite its name fatal
is not special, it can be rescued. If you are looking for a way to end your program maybe best call the global exit
method?
begin
raise FatalError.new
rescue Exception => e
puts "Not so fatal after all..."
end
Short answer is, you can, but probably shouldn't. This exception is reserved for Ruby internals. It is effectively hidden to users by being a constant with an all lowercase identifier. (Ruby won't do a constant lookup unless the identifier starts with an uppercase character.)
fatal
NameError: undefined local variable or method `fatal' for main:Object
The same is true when using Object#const_get
:
Object.const_get(:fatal)
NameError: wrong constant name fatal
If this exception class was intended for us to use, then it would be readily available, and not hidden away.
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