Method Call in Exception

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • mwt

    Method Call in Exception

    In my latest attempt at some Python code, I've been tempted to write
    something in the form of:

    try:
    [...] #doing some internet stuff
    except IOError:
    alternate_metho d_that_doesnt_n eed_internet()

    This works when I try it, but I feel vaguely uneasy about putting
    method calls in exception blocks. So tell me, Brave Pythoneers, is this
    evil sorcery that I will end up regretting, or is it just plain good
    ol' Python magic?

  • Felipe Almeida Lessa

    #2
    Re: Method Call in Exception

    Em Qua, 2006-04-19 às 16:54 -0700, mwt escreveu:[color=blue]
    > This works when I try it, but I feel vaguely uneasy about putting
    > method calls in exception blocks.[/color]

    What do you put in exception blocks?!

    [color=blue]
    > So tell me, Brave Pythoneers, is this
    > evil sorcery that I will end up regretting, or is it just plain good
    > ol' Python magic?[/color]

    IMHO, the exception block in Python is used a lot in places where you
    could use an if-then-else, like your example that could be written as

    if internet_availa ble():
    [...] #doing some internet stuff
    else:
    alternate_metho d_that_doesnt_n eed_internet()

    So yes, I think there's no problem there.

    --
    Felipe.

    Comment

    • mwt

      #3
      Re: Method Call in Exception


      Felipe Almeida Lessa wrote:[color=blue]
      > Em Qua, 2006-04-19 às 16:54 -0700, mwt escreveu:[color=green]
      > > This works when I try it, but I feel vaguely uneasy about putting
      > > method calls in exception blocks.[/color]
      >
      > What do you put in exception blocks?![/color]

      Usually I just print an error message.
      [color=blue]
      >
      >[color=green]
      > > So tell me, Brave Pythoneers, is this
      > > evil sorcery that I will end up regretting, or is it just plain good
      > > ol' Python magic?[/color]
      >
      > IMHO, the exception block in Python is used a lot in places where you
      > could use an if-then-else, like your example that could be written as
      >
      > if internet_availa ble():
      > [...] #doing some internet stuff
      > else:
      > alternate_metho d_that_doesnt_n eed_internet()
      >
      > So yes, I think there's no problem there.
      >[/color]

      Normally I don't like to use exception blocks to do condition-statement
      stuff. At least that is how my Java training has programmed me. But in
      this case, the condition is whether the internet connection is working
      or not, and I don't see any other way to do it. And furthermore, I
      don't know if the exceptions-as-logic is a no-no in Python. Hence the
      question.

      Comment

      • Serge Orlov

        #4
        Re: Method Call in Exception

        Felipe Almeida Lessa wrote:[color=blue]
        > Em Qua, 2006-04-19 às 16:54 -0700, mwt escreveu:[color=green]
        > > This works when I try it, but I feel vaguely uneasy about putting
        > > method calls in exception blocks.[/color]
        >
        > What do you put in exception blocks?!
        >
        >[color=green]
        > > So tell me, Brave Pythoneers, is this
        > > evil sorcery that I will end up regretting, or is it just plain good
        > > ol' Python magic?[/color]
        >
        > IMHO, the exception block in Python is used a lot in places where you
        > could use an if-then-else, like your example that could be written as
        >
        > if internet_availa ble():
        > [...] #doing some internet stuff
        > else:
        > alternate_metho d_that_doesnt_n eed_internet()
        >
        > So yes, I think there's no problem there.[/color]

        What if the service is overloaded and always times out? For end user
        it's basically the same as there is no internet access. I routinely use
        the following pattern:

        unrecoverable = MemoryError, IOError
        try:
        do_your_best()
        except unrecoverable, e:
        util.help_on_er ror(e)
        sys.exit(1)

        def do_your_best():
        recoverable = IOError, socket.error, SomeOtherError
        try:
        do_something()
        except recoverable, e:
        do_something_el se()

        Comment

        • Carl Banks

          #5
          Re: Method Call in Exception

          mwt wrote:[color=blue]
          > In my latest attempt at some Python code, I've been tempted to write
          > something in the form of:
          >
          > try:
          > [...] #doing some internet stuff
          > except IOError:
          > alternate_metho d_that_doesnt_n eed_internet()
          >
          > This works when I try it, but I feel vaguely uneasy about putting
          > method calls in exception blocks. So tell me, Brave Pythoneers, is this
          > evil sorcery that I will end up regretting, or is it just plain good
          > ol' Python magic?[/color]

          It's ok. In fact a lot of Pythonistas recommend this way over the
          alternative, even when you don't have to. For example, a lot of people
          recommend this:

          try:
          name = record.name
          except AttributeError:
          name = "Freddy"

          instead of this:

          if hasattr(record, "name"):
          name = record.name
          else:
          name = "Freddy"

          I prefer the latter most of the time; however, sometimes (as it appears
          in your case) simply trying it and doing something else if it raises an
          exception is easier, more straightforward , and more robust than
          explicitly testing the condition. One thing to consider is whether
          something you don't expect could throw the same exception; might have
          to disambiguate them somehow in the except block.

          Language-wise, I doubt there are any serious gotchas whem running
          regular (as opposed to error handling) code in an except block. So go
          right ahead; no need to feel guilty about it.


          Carl Banks

          Comment

          • Duncan Booth

            #6
            Re: Method Call in Exception

            Carl Banks wrote:
            [color=blue]
            > In fact a lot of Pythonistas recommend this way over the
            > alternative, even when you don't have to. For example, a lot of people
            > recommend this:
            >
            > try:
            > name = record.name
            > except AttributeError:
            > name = "Freddy"
            >
            > instead of this:
            >
            > if hasattr(record, "name"):
            > name = record.name
            > else:
            > name = "Freddy"
            >
            >[/color]

            In this specific case, either of these would be better written as:

            name = getattr(record, 'name', 'Freddy')

            Comment

            • bruno at modulix

              #7
              Re: Method Call in Exception

              mwt wrote:
              (snip)[color=blue][color=green][color=darkred]
              >>>This works when I try it, but I feel vaguely uneasy about putting
              >>>method calls in exception blocks.[/color]
              >>
              >>What do you put in exception blocks?![/color][/color]

              Whatever fits the specific case...

              (snip)[color=blue]
              > Normally I don't like to use exception blocks to do condition-statement
              > stuff. At least that is how my Java training has programmed me.[/color]


              [color=blue]
              > But in
              > this case, the condition is whether the internet connection is working
              > or not, and I don't see any other way to do it.[/color]

              As Felipe wrote, you could also use a if/else.

              [color=blue]
              > And furthermore, I
              > don't know if the exceptions-as-logic is a no-no in Python.[/color]

              It's not.

              The main guideline here is that a else/if has a constant cost - the test
              is always executed -, while a try/except only adds overhead if it's
              fired. So - if you leave out purely stylistic or religious
              considerations - the 'good' choice depends mostly on the 'cost of the
              test'/'cost of the exception' ratio and the 'have connection'/'no
              connection' ratio.

              --
              bruno desthuilliers
              python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
              p in 'onurb@xiludom. gro'.split('@')])"

              Comment

              • bwaha

                #8
                Re: Method Call in Exception


                "mwt" <michaeltaft@gm ail.com> wrote in message
                news:1145490879 .789439.18030@t 31g2000cwb.goog legroups.com...[color=blue]
                > In my latest attempt at some Python code, I've been tempted to write
                > something in the form of:
                >
                > try:
                > [...] #doing some internet stuff
                > except IOError:
                > alternate_metho d_that_doesnt_n eed_internet()
                >[/color]
                I'm only a hack at programming but where I find try: blocks useful is where
                I have multiple statements within the try: block, any one or more of which
                can produce an exception. I just want to trap a failure and get out of
                there. This happens to me for any number of reasons when I drive other apps
                through the com interface. (In my job I just write simple apps to make my
                job easier, not bomb-proof customer-focused code). So in your case perhaps
                you have open connection, find site, get data within the try block, and exit
                gracefully if any one fails. How you use it depends on what level of detail
                you need.

                bwaha



                Comment

                • Kent Johnson

                  #9
                  Re: Method Call in Exception

                  Carl Banks wrote:[color=blue]
                  > mwt wrote:[color=green]
                  >> In my latest attempt at some Python code, I've been tempted to write
                  >> something in the form of:
                  >>
                  >> try:
                  >> [...] #doing some internet stuff
                  >> except IOError:
                  >> alternate_metho d_that_doesnt_n eed_internet()
                  >>
                  >> This works when I try it, but I feel vaguely uneasy about putting
                  >> method calls in exception blocks. So tell me, Brave Pythoneers, is this
                  >> evil sorcery that I will end up regretting, or is it just plain good
                  >> ol' Python magic?[/color]
                  >
                  > It's ok. In fact a lot of Pythonistas recommend this way over the
                  > alternative, even when you don't have to. For example, a lot of people
                  > recommend this:
                  >
                  > try:
                  > name = record.name
                  > except AttributeError:
                  > name = "Freddy"
                  >
                  > instead of this:
                  >
                  > if hasattr(record, "name"):
                  > name = record.name
                  > else:
                  > name = "Freddy"[/color]

                  or maybe
                  name = getattr(record, 'name', 'Freddy')

                  Kent

                  Comment

                  Working...