From: Mario Antonetti Date: 2010-04-07T00:23:05+09:00 Subject: Re: Custom Exceptions --0015174733da759408048393059c Content-Type: text/plain; charset=ISO-8859-1 On Tue, Apr 6, 2010 at 9:44 AM, Leslie Viljoen wrote: > Hi everyone > > I want to make a custom exception like so: > > class BillRowError < StandardError > def initialize(field, index) > @field = field > @index = index > end > end > > I'll call this like so: > raise(BillRowError.new(:roamingcalls, @index), "Roaming Calls field > missing") if n.length == 0 > > But now I'd like to be able to modify the string that Ruby prints when the > exception is not rescue'd. I thought I could add this method to the > BillRowError class: > > def message > @message + " field: #{@field}, row: #{@index}" > end > > That almost works but I get a "instance variable @message not initialized" > warning, which means Ruby is not setting @message in my object like I > expected. Making my own message= method doesn't help. > > Can an exception object access and modify the message that gets passed in > the "raise"? > You could try rewriting the to_s method and take advantage of the inheritance: def to_s super + " field: #{@field}, row: #{@index}" end That worked for me. I'm not sure if this is the recommended solution. --0015174733da759408048393059c--