You can create a subclass of an exception to make it more descriptive, but how should you set the default 'message'?
class MyError < StandardError # default message = "You've triggered a MyError" end begin raise MyError, "A custom message" rescue Exception => e p e.message end begin raise MyError raise Exception => e p e.message end
The first should output 'A custom message'
The second should output 'You've triggered a MyError'
Any suggestions as to best practice?
An exception is an unwanted or unexpected event, which occurs during the execution of a program, i.e. at runtime, that disrupts the normal flow of the program's instructions. In Ruby, descendants of an Exception class are used to interface between raise methods and rescue statements in the begin or end blocks.
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.
The class Exception and its subclasses are a form of Throwable that indicates conditions that a reasonable application might want to catch. The class Exception and any subclasses that are not also subclasses of RuntimeException are checked exceptions.
StandardError is a superclass with many exception subclasses of its own, but like all errors, it descends from the Exception superclass. StandardErrors occur anytime a rescue clause catches an exception without an explicit Exception class specified.
Define an initialize method, which takes the message as an argument with a default value. Then call StandardError
's initialize method with that message (using super
).
class MyError < StandardError def initialize(msg = "You've triggered a MyError") super(msg) end 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