Exception handling
1 #! Usr/bin/env python2 #-*-coding:utf-8-*-3 #Author Calmyan4 5list_l=['g','h']6data={'a':'3'}7 Try:8 #list_l[3] #IndexError: List index out of range9data['2q']Ten exceptIndexerror as E:#list subscript out of bounds One Print(e) A exceptKeyerror as E:#Dictionary key does not exist - Print('without this key', E) - exceptException as E:##大部分异常都可捕获 the Print(e) - Else:#combined Use - Print('above normal') - finally: + Print('And then you print it all .')
Exception type:
" " "Common exception attributeerror attempts to access a tree that does not have an object, such as foo.x, but Foo does not have a property xioerror input/output exception; it is basically impossible to open a file importerror cannot introduce a module or package is basically a path problem or name error Indentationerror syntax error (subclass); The code is not aligned correctly indexerror the subscript index exceeds the sequence boundary, for example, when X has only three elements, it attempts to access the X[5]keyerror Attempting to access a key that does not exist in the dictionary Keyboardinterrupt CTRL + C is pressed Nameerror use a variable that has not been assigned to the object SyntaxError Python code is illegal, the code cannot be compiled TypeError The incoming object type is incompatible with the required unboundlocalerror attempt to access a local variable that has not yet been set, basically because there is another global variable with the same name, causing you to think that you are accessing it valueerror pass in a value that the caller does not expect, even if the type of the value is correct " '"
Custom exceptions
1 #! Usr/bin/env python2 #-*-coding:utf-8-*-3 #Author Calmyan4 5 classNewexception (Exception):#inheriting base class exceptions6 " "Custom Exception Information" "7 def __init__(self,msg):8Self.message=msg9 Ten def __str__(self):#Not defined, the base class already has One #Return self.message# returns exception information A return 'Trigger Custom Exception ...'# - - Try: the RaiseNewexception ('triggering a custom exception') - exceptnewexception as E: - Print(e)
Socket communication
Python 37th Day-Exception--socket