tags:

views:

30

answers:

1

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?

+2  A: 

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
sepp2k
Just `super` is enough. If you call `super` without an argument list, it will simply pass on all arguments, which is why, when you actually want to pass *no* arguments, you must explicitly call `super()`.
Jörg W Mittag