[Tutor] Stack unwind using exceptions.

Kent Johnson kent37 at tds.net
Sun Jul 5 00:25:17 CEST 2009


On Sat, Jul 4, 2009 at 3:56 PM, Noufal Ibrahim<noufal at nibrahim.net.in> wrote:
> Hello everyone,
>
> Would it be considered unorthodox or 'wrong' in some sense for me to use an
> exception to unwind the stack and return to a caller for a recursive
> function?
>
> I need to do a depth first search and when I find the right element to just
> stop the whole thing, and get back to the caller saying that I found it.

Why not just return the value from the function and pass it up the
call chain? If a call fails return None. Something like this:

def search(self, value):
  if self.value == value:
    return self

  for child in self.children:
    result = child.search(value)
    if result is not None:
      return result

  return None

Kent


More information about the Tutor mailing list