How to stop nested catch from looking messy?


#1

I’m writing a parser generator (for fun) and am making use of
throw/catch to allow notification of special parse events to “bubble
up” through many levels. The trouble is that the code starts to look
ugly when I have to nest various catch blocks so as to catch three
different possible types of throw.

Check out the following loop where I am iterating over a collection of
“parseable” objects, catching and counting the different types of
throws. The “parseable” object could be something as simple as a String
or a complex hierarchy of parslets and parslet combinations; the main
point here is that I don’t know what it is nor what type of throw it
might do, I only know that it should respond to the “parse” message:

alternatives.each do |parseable|
catch(:ProcessNextAlternative) do
catch(:NotPredicateSuccess) do
catch(:AndPredicateSuccess) do
catch(:ZeroWidthParseSuccess) do
accumulate_result(parseable.parse)
match_count += 1
throw :ProcessNextAlternative
end
zero_width_count += 1
throw :ProcessNextAlternative
end
and_predicate_count += 1
throw :ProcessNextAlternative
end
not_predicate_count += 1
end
end

Does this design stink? Is there a better/cleaner way?

Cheers,
Greg