18 Apr 18 Exception Handling Network Programming

18 Apr 18
1. Exception handling
1. What is an exception
    An exception is a signal that an error occurs. Once a program fails, if there is no corresponding processing mechanism in the program, an exception will be thrown for the error, and the program will be terminated.
 
2. An exception is divided into three parts:
    1. Abnormal tracking information
    2. Types of exceptions
    3. Unusual values
 
3. Exception classification:
    1. Syntax exception:
        Such exceptions should be corrected before program execution
        print('start....')
        x=1
        x+=1
        if
        print('stop....')
 
    2. Logical exception
 
4. Common logical exceptions
IndexError
l=['a','b']
l[100]
 
KeyError
d={'a':1}
d['b']
 
AttributeError:
class Foo:
    pass
Foo.x
import them
os.aaa
 
ZeroDivisionError
1 / 0
 
FileNotFoundError
f=open('a.txt','r',encoding='utf-8')
 
ValueError: I/O operation on closed file.
f=open('a.txt','r',encoding='utf-8')
f.close()
f.readline()
 
ValueError: invalid literal for int() with base 10: 'aaaaa'
int('aaaaa')
 
TypeError
for i in 333:
    pass
 
NameError
x
func()
 
def func():
    import them
    os.xxxx
func()
 
5. Grammar:
try does not affect the operation of the normal program, and jumps to the except judgment when encountering an exception
single branch
try:
    print('start.....')
    x=1
    and
    l=[]
    l[3]
    d={'a':1}
    d['b']
    print('end....')
except NameError:
    print('variable name is not defined')
print('other.....')
 
multi-branch
try:
    print('start.....')
    x=1
    # and
    l=[]
    l[3]
    d={'a':1}
    d['b']
    print('end....')
except NameError:
    print('variable name is not defined')
except KeyError:
    print('The key of the dictionary does not exist')
except IndexError:
    print('Index out of range of list')
print('other.....')
 
Multiple exceptions are handled by the same piece of logic
try:
    print('start.....')
    x=1
    # and
    l=[]
    # l[3]
    d={'a':1}
    d['b']
    print('end....')
except (NameError,KeyError,IndexError):
    print('There is a problem with the variable name or the key of the dictionary or the index of the list')
print('other.....')
 
Universal exception
try:
    print('start.....')
    x=1
    # and
    l=[]
    # l[3]
    d={'a':1}
    # d['b']
    import them
    os.aaa
    print('end....')
except Exception:
    print('Universal exception---"')
print('other.....')
 
get abnormal value
try:
    print('start.....')
    x=1
    and
    l=[]
    l[3]
    d={'a':1}
    d['b']
    import them
    os.aaa
    print('end....')
except Exception as e: # except NameError as e:
    print('Universal exception---"',e)
print('other.....')
 
try:
    print('start.....')
    x=1
    # and
    l=[]
    l[3]
    d={'a':1}
    d['b']
    import them
    os.aaa
    print('end....')
except NameError as e:
    print('NameError: ',e)
except KeyError as e:
    print('KeyError: ',e)
except Exception as e:
    print('Universal exception---"',e)
print('other.....')
 
try....else...
else: cannot be used alone, must be used in conjunction with except, which means: the sub-code block of else will be executed without any exceptions in the detected code
 
try:
    print('start.....')
    # x=1
    # # and
    # l=[]
    # l[3]
    # d={'a':1}
    # d['b']
    # import the
    # os.aaa
    print('end....')
except NameError as e:
    print('NameError: ',e)
except KeyError as e:
    print('KeyError: ',e)
except Exception as e:
    print('Universal exception---"',e)
else:
    print('Execute without any exception in the detected code block')
print('other.....')
 
try...finally....
try:
    print('start.....')
    # x=1
    # # and
    # l=[]
    # l[3]
    # d={'a':1}
    # d['b']
    # import the
    # os.aaa
    print('end....')
except NameError as e:
    print('NameError: ',e)
except KeyError as e:
    print('KeyError: ',e)
except Exception as e:
    print('Universal exception---"',e)
else:
    print('Execute without any exception in the detected code block')
finally:
    print('Whether there is an exception or not, it will be executed')
print('other.....')
 
The code that recycles system resources is usually placed in the sub-code block of finally
try:
    f=open('a.txt',mode='w',encoding='utf-8')
    f.readline()
finally:
    f.close()
print('other....')
 
try+except
try+except+else
try+finally
try+except+else+finally
 
6. Actively trigger exceptions
raise TypeError('type error')
 
class People:
    def __init__(self,name):
        if not isinstance(name,str):
            raise TypeError('%s must be of type str' %name)
        self.name=name
p=People(123)
 
7, affirmation
print('part1........')
# stus=['igon','alex','wxx','lxx']
stus=[]
 
# if len(stus) <= 0:
#     raise TypeError
 
assert len(stus) > 0
 
print('part2.........')
print('part2.........')
print('part2.........')
print('part2.........')
print('part2.........')
print('part2.........')
 
8. Custom exception
class RegisterError(BaseException):
    def __init__(self,msg,user):
        self.msg=msg
        self.user=user
    def __str__(self):
        return '<%s:%s>' %(self.user,self.msg)
raise RegisterError('Registration failed','teacher')
 
Use if when you can know when the exception is, use try when you know there is an exception but you are not sure what the exception is, etc.
Minimize the use of try, etc. to avoid making the structure look too complicated
age=input('>>: ').strip() #age='aaa'
 
if age.isdigit():
    age=int(age)
 
    if age > 10:
        print('too big')
    elif age < 10:
        print('too small')
    else:
        print('you got it')
 
2. Network programming
1. C/S, B/S architecture
   client<------>server
   browser<------>server
   Learning socket programming is to write a client software and server software, and then implement network-based communication between the server and the client.
 
2. What is a network?
    1. Physical connection medium
    2. Internet Protocol
       Internet Protocol is a bunch of standards
       Metaphor: Internet Protocol is the English of the computer world
 
3, osi five-layer protocol (there are four layers, there are seven layers, mainly five layers)
Application layer: such as HTTP, mail, ftp, programmer-defined
Transport layer: TCP/UDP, works based on ports, finds which application in the computer is through the port
Network layer: IP protocol, find the local area network by IP address
Data link layer: The Ethernet Ethernet protocol searches the computer through the mac address in the local area network, and specifies the grouping standard
Physical layer: send electrical signal 01010101

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324550524&siteId=291194637