#1
  1. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2003
    Location
    India
    Posts
    177
    Rep Power
    22

    Ignoring exceptions


    How to ignore exceptions in Python? If I want to resume after an exception, how can I do it?

    I would like to ignore the exception and resume after the statement which caused that exception.
  2. #2
  3. Mini me.
    Devshed Novice (500 - 999 posts)

    Join Date
    Nov 2003
    Location
    Cambridge, UK
    Posts
    783
    Rep Power
    14
    The solution is to wrap code in a try/except structure.

    The simplest but also the worst solution is this:
    python Code:
    try:
        #all my code goes here
        a = 1/0
    except:
        print "I will ignore every exception"
    print "Carry on..."


    Recomended reading

    The standard exceptions are listed here:
    Exceptions
    and you use them like this:
    python Code:
    mylist = [0,]
    for n in [0,1]:
        try:
            a = 1/mylist[n]
        except ZeroDivisionError:
            print "A divide by zero error"
        except IndexError:
            print "An index error"
    print "Carry on..."


    To summarise:
    • Make exceptions specific to the problem - understand how your code can fail
    • Only put essential code in the try section.
    • use finally to guarantee operation such as closing down links or files


    grim

    Comments on this post

    • netytan agrees : You can put a pass in the place of print to carry on silently :)
    • Scorpions4ever agrees : Adding rep for netytan
    • bhagwatn agrees
    • xlordt agrees : Say thanx to netytan ;) nice one
    Last edited by Grim Archon; February 21st, 2006 at 06:00 AM.
  4. #3
  5. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2003
    Location
    India
    Posts
    177
    Rep Power
    22
    Thanks Grim.
    Actually I was experimenting with exception handling with the following code and somehow wanted to resume execution after the first exception. But looks like it is not possible that way.
    Code:
    # exception handling example #1
    def f1(): 1/0
    def f2():
        t = (10,20)
        t[0] = t[0] + 1
    def f3(): "A" + 1
    def f4():
        d = {}
        return d['xyz']
    def f5():
        print "error free function!"
    try:
         f1() # raises exception
         f2() # is there any way to resume from here?
         f3()
         f4()
         f5()
    except ZeroDivisionError, value:
         print "** divide by zero err **", value
    except TypeError, value:  
         print "** invalid numeric oprn **", value
    except TypeError, value:  
         print "** invalid numeric open **", value
    except KeyError, value:  
         print "** non-existing key passed **", value
    else:
         print "No exception catched"
    So, I modified the code in the following way which did the trick and allowed to execute all functions and see all the exceltions
    Code:
    # exception handling example #2
    def f1(): 1/0
    def f2():
        t = (10,20)
        t[0] = t[0] + 1
    def f3(): "A" + 1
    def f4():
        d = {}
        return d['xyz']
    def f5():
        print "error free function!"
    funList = [f1,f2,f3,f4,f5]
    for fun in funList:
      try:
         fun()
      except ZeroDivisionError, value:
         print "** divide by zero err **", value
      except TypeError, value:  
         print "** invalid numeric oprn **", value
      except TypeError, value:  
         print "** invalid numeric open **", value
      except KeyError, value:  
         print "** non-existing key passed **", value
      else:
         print "No exception catched"
  6. #4
  7. Mini me.
    Devshed Novice (500 - 999 posts)

    Join Date
    Nov 2003
    Location
    Cambridge, UK
    Posts
    783
    Rep Power
    14
    With the code you first wrote - your main routine does not care about exceptions within the functions. In that case put the exception handling in the functions themselves and just make the function return a sensible answer if an exception is raised.

    grim
  8. #5
  9. Hello World :)
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2003
    Location
    Hull, UK
    Posts
    2,537
    Rep Power
    69
    I never really got what everyone sees in exception handling, it seems to me a last ditch approach at writing a program that [hopefully] wont break down.

    All of these exceptions could be handled by checking before the program freaks out . Or in some cases writing code that performs as expected. That's not to say that they aren't useful but in a well written program it should be impossible for an error to occurs no? You've covered all your angles.

    For educational reasons I can see why you'd want to carry on but this isn't generally very useful in larger programs because you need to do something with the value raising the value.

    If this is reading a file for instance then you'd best walk away gracefully . If you can provide an alternative value to work with that's fine but this isn't usually the case for obvious reasons.

    I would learn how to use exception handling so you don't ever have to use it; but for no other reason.

    Grimy, nice posts! I'm out of rep to give you right now . We should coordinate or something.

    Take care .

    Mark.

    Comments on this post

    • Grim Archon agrees : Cheers Mark, have some of mine :)
    programming language development: www.netytan.com Hula

  10. #6
  11. Mini me.
    Devshed Novice (500 - 999 posts)

    Join Date
    Nov 2003
    Location
    Cambridge, UK
    Posts
    783
    Rep Power
    14
    Thanks Mark I'll take your virtual reps any day

    Actually, exceptions have a couple of "good" uses and whether you like them depends on your coding style.

    It allows the coder to write concentrating on the logic of the problem to be solved. It is relatively easy to code adding the exception handling to make it robust. This keeps the logic focused on the problem to be solved. Without exceptions the checking logic can be bigger than the actual program you wanted .

    grimy
  12. #7
  13. Banned ;)
    Devshed Supreme Being (6500+ posts)

    Join Date
    Nov 2001
    Location
    Woodland Hills, Los Angeles County, California, USA
    Posts
    9,643
    Rep Power
    4248
    Exceptions should be used to signal errors that cannot be handled locally, such as the failure to acquire a resource in an object's constructor.

    Stroustrup's advice:
    Do not use exceptions as simply another way to return a value from a function. Most users assume - as the language definition encourages them to - that exception-handling code is error-handling code, and implementations are optimized to reflect that assumption.
    This advice holds true for other languages besides C++.

    P.S. I added rep in place of you Mark .

    Comments on this post

    • Grim Archon agrees : Can't argue with that :)
    Up the Irons
    What Would Jimi Do? Smash amps. Burn guitar. Take the groupies home.
    "Death Before Dishonour, my Friends!!" - Bruce D ickinson, Iron Maiden Aug 20, 2005 @ OzzFest
    Down with Sharon Osbourne

    "I wouldn't hire a butcher to fix my car. I also wouldn't hire a marketing firm to build my website." - Nilpo
  14. #8
  15. Hello World :)
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2003
    Location
    Hull, UK
    Posts
    2,537
    Rep Power
    69
    Originally Posted by Grim Archon
    Thanks Mark I'll take your virtual reps any day

    Actually, exceptions have a couple of "good" uses and whether you like them depends on your coding style.

    It allows the coder to write concentrating on the logic of the problem to be solved. It is relatively easy to code adding the exception handling to make it robust. This keeps the logic focused on the problem to be solved. Without exceptions the checking logic can be bigger than the actual program you wanted .

    grimy
    They're not something I inherently dislike. I do dislike the way they're used to control program flow .

    If you build the program up to check the things you expect to go wrong then you can avoid controlling program flow by rebounding from error to error; you obviously have some idea of what might cause problems to use exception handling anyway.

    Exception handling in provides a way of recovering from an error however most of the time you just want to leave anyway. If you can avoid errors, which I think all programs should strive to do then they really serve little point.

    They have their uses, but that should be to catch unexpected errors and act on them gravefully. IMO the overuse of exception handling leads to poor program logic which is exactly what you don't want .

    Soon as I can give you more rep I will, but apparently I have to wait .

    Later bro,

    Mark.

    Edit: Thanks Scorpi very handy
    Last edited by netytan; February 21st, 2006 at 03:09 PM.
    programming language development: www.netytan.com Hula

  16. #9
  17. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2003
    Location
    India
    Posts
    177
    Rep Power
    22

    My original question is still unanswered.


    Exceptions can be caught and ignored, or allwed to pass and terminate a program with a standard error message.

    Above is from Learning Python book 2nd Ed, from Mark Lutz. Above sentence confused me and gave me a feeling that one can IGNORE exceptions.

    I'm clear about catching exceptions, but still not clear about how to ignore them.
  18. #10
  19. Hello World :)
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2003
    Location
    Hull, UK
    Posts
    2,537
    Rep Power
    69
    Originally Posted by bhagwatn
    Exceptions can be caught and ignored, or allwed to pass and terminate a program with a standard error message.

    Above is from Learning Python book 2nd Ed, from Mark Lutz. Above sentence confused me and gave me a feeling that one can IGNORE exceptions.

    I'm clear about catching exceptions, but still not clear about how to ignore them.
    I would take that as you can catch an except and do nothing with it, this is IMO what was meant by ignoring the exception .

    Not catching the exception at all, which would of course result in Python exiting is more correctly you are ignoring the exception entirely. Badly written maybe, it depends on the context .

    Examples:

    Code:
    try:
        ...code with error...
    except SomeErrorType:
        ...do something to recover or exist gracefully...
    Code:
    try:
        ...code with error...
    except SomeErrorType:
        pass # do nothing at all just ignore the error and carry on.
    Code:
    ...code with error...
    Error: Exit Python with ugly error message.
    $
    The second example here shows how I would "ignore" an error, if I ever just ignored an error .

    Hope this helps,

    Mark.
    programming language development: www.netytan.com Hula

  20. #11
  21. Mini me.
    Devshed Novice (500 - 999 posts)

    Join Date
    Nov 2003
    Location
    Cambridge, UK
    Posts
    783
    Rep Power
    14
    great answers guys (and thanks all for the reps).

    grim

IMN logo majestic logo threadwatch logo seochat tools logo