我正在将源文件拆分为令牌,特别是扫描标识符。但是,要求标识符长达30个字符。当一个标识符达到这个长度时,我会发出一条异常消息:'Identifiers can only be 30 characters long, truncating..'
。在引发异常后保留变量
这是应该如何,但是当我提出这个异常时,我跳出了我的方法,在我能够存储它之前扫描标识符。我需要以某种方式提出异常并保留迄今收集的标识符。任何想法如何做到这一点?
# classify each character, and call approriate scan methods
def tokenize()
@infile.each_char do |c|
begin
case c
when /[a-zA-Z\$]/
scan_identifier(c)
when /\s/
#ignore spaces
else
#do nothing
end
rescue TokenizerError => te
puts "#{te.class}: #{te.message}"
end
end
end
# Reads an identifier from the source program
def scan_identifier(id)
this_id = id #initialize this identifier with the character read above
@infile.each_char do |c|
if c =~ /[a-zA-Z0-9_]/
this_id += c
# raising this exception leaves this function before collecting the
# truncated identifier
raise TokenizerError, 'Identifiers can only be 30 characters long, truncating..' if this_id.length == 30
else
puts "#{this_id}"
break # not part of the identifier, or an error
end
end
end
例外应仅用于“例外”情况。不要试图用它们创建程序流。只需从您的方法中返回令牌。 – 2012-02-08 05:10:03
这不是一个程序流程问题。我需要向正在使用该程序的人发出警告,说明他们的标识符太长,并且正在被截断。我认为一个例外将是这样做的合理方法。什么会是一个很好的选择? – 2012-02-08 05:11:59
让我把它变成一个答案。 – 2012-02-08 05:28:02