简体   繁体   中英

Trapping an error in python

I am trying to trap error and let the code finish running. In the code below, I "do Something." if fails, I want to print Error Msg and continue running the second half.

What is happening is When an error occurs with the first section, The error statement print and stops running. I would like the code to keep running past the first section.

  if len(rows) > 0:
            try:                
                print "Do something"       
            except:
                print time.strftime("%H:%M:%S")  

            try:
                print "Do somethings else"
            except:
                print time.strftime("%H:%M:%S")  

Python's exceptions don't have a built-in restart capability to "continue running the second half". Instead, you just need to move the "unconditional, always do this" part out of the try-clause and into a finally-clause or outside the try-statement altogether.

PS It is usually ill-advised to swallow all exceptions with a bare except-clause. Instead, the usual best practice is to catch only the exceptions you know how to handle.

Can you programmatically determine if 'do Something' failed? If so, that's a better way to go rather than just relying on an exception handling mechanism. I see this anti-pattern a lot in .net code. Exceptions, in many languages, are intended for exceptional circumstances, not just error handling.

Keeping answer just to preserve comments for those who might think like I did.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM