1, Python under the exception how to deal with:
1 #Encoding=utf-82 3 """4 Python encounters an exception and the program runs directly5 Try:6 "Judging the code with the potential to throw an exception"7 print "haha"8 except:9 "code to run under exception "Ten Else: One "Run logic without exception" A finally: - "The code always executes regardless of the try judgment." - the reasonable use of exceptions: - 1, have to use the place to use the anomaly; - 2. Correct use of exceptions: exceptions need to be captured - For example: except IOError: + - """ + AA = [1, 2, 3, 4, 5, 6] at - PrintA[4] - - Try: - PrintA[6] - except: in PrintU'haha' - to Print "continue to be here ." + - the Try: * PrintA[6] $ except:Panax Notoginseng Print "Huhu" - Else: the Print "HoHo" + finally: A Print "hehe" the + - ImportUrllib $Sth_url ="HTTP://WSDFSDF" $ - Try: -D =Urllib.urlopen (Sth_url) the except: - Print "something went wrong."Wuyi Else: theContent =D.read () - finally: Wu Pass - #d.close () About $ """ - note of the exception: - 1, a try corresponding to a except - 2, using Python built-in exception, to correspond to their own situation; A Ioerro, Indexerror + 3, the way to catch the exception: the Import Logging - logger = Logging.getlogger () $ #logfile = ' Excetion_demo.log ' #log文件名 the HDLR = logging. Filehandler ('/tmp/sendlog.txt ') the formatter = logging. Formatter ('% (asctime) s% (levelname) s% (message) s ') the Hdlr.setformatter (Formatter) the Logger.addhandler (HDLR) #logging绑定 - Logger.setlevel (logging. NOTSET) in the the Import sys, logging About Try: the d = urllib.urlopen ("www.kdkdk.com") the except: the exc = Sys.exc_info () + loggin.debug (exc[1] - Print Exc[1] the Print excBayi 4. Assert, Assert the assert expression, "throw a message after an error" the assert 1>4, "Expression Error" - First, assert the error that absolutely cannot occur, and then handle the exception; - """ the the """ the With usage: automatic recycling of garbage the #进入时, the __enter__ of the calling object - #退出时, the __exit__ function of the calling object the the d = open (' A ', ' R ') the D.read ()94 d.close () the the with open (' A ', ' R ') as D: the content = A.read ()98 """ About - #With Example:101 classSth (object):102 def __init__(self, Xixi):103SELF.A =Xixi104 the def __enter__(self):106 PrintU'haha, come in.'107 returnSELF.A108 109 def __exit__(self, type, value, Traceback): the PrintU'haha, out.'111 theWith STH ("GG") as S:113 PrintS#S is __enter__ return value the the """ the to define your own exception class117 """118 119 classmyexception (Exception): - def __init__(self, Error, msg):121Self.args =(Error, MSG)122Self.error =Error123Self.msg =msg124 the Try:126 RaiseMyException (1,"My Exception")127 exceptException as E: - PrintSTR (e)
Exception handling under Python