abnormal
1. What is an exception
An exception is a signal of a program error. Once an error occurs in the program, an exception will be generated. If it is not handled in the program, the exception will be thrown, and the operation of the program will be terminated. In Python, the exceptions triggered by errors are as follows There are two kinds of errors. One is syntax error, which should be corrected before the program runs
>>> if File "<stdin>", line 1 if ^ SyntaxError: invalid syntax
The other is logic errors, common logic errors such as
# TypeError: numeric type cannot be added to string type 1+'2' # ValueError: when the string contains a non numeric value, it cannot be converted to int type num=input(">>: ") #Enter hello int(num) # NameError: a nonexistent name x is referenced x # IndexError: the index exceeds the limit of the list l=['egon','aa'] l[3] # KeyError: refers to a key that does not exist dic={'name':'egon'} dic['age'] # AttributeError: the referenced attribute does not exist class Foo: pass Foo.x # ZeroDivisionError: divisor cannot be 0 1/0
2. Why are exceptions handled
In order to enhance the robustness of the program, even if there is an error in the running process of the program, do not terminate the program, but catch and handle the exception: record the error information in the log
3. How to handle exceptions?
3.1 syntax error, processing method 1: it must be corrected before the program runs
if 1 > 3 print("run...")
3.2 logical error
print(x) l = ['a', 'b'] l[2] 1/0 int('abc') dic = {'name': 'egon'} dic['age'] class Foo: pass Foo.x
There are two processing methods for logical exceptions
- The condition of error occurrence is predictable, and if judgment is used to solve it
age = input('>>: ').strip() # As long as the input is not a number, an error will occur if age.isdigit(): age = int(age) if age > 18: print('Guess big') elif age < 18: print('Guess big') else: print('You guessed right') else: print('You must enter a number')
- The conditions under which errors occur are unpredictable
print('start...') try: # Code that may throw exceptions Subcode 1 Subcode 2 Subcode 3 except Exception type 1 as e: pass except Exception type 2 as e: pass ... else: If no exception occurs in the detected sub code block, it will be executed else Subcode of finally: No matter whether the detected sub code block has an exception or not, it will be executed finally Subcode of print('end...')
If we want to handle multiple types of exceptions with one logic, we can put multiple exceptions into a tuple and match them with an exception
try: Detected code block except (NameError,IndexError,TypeError): trigger NameError or IndexError or TypeError Processing logic corresponding to give an example def convert_int(obj): try: res=int(obj) except (ValueError,TypeError): print('argument must be number or numeric string') res=None return res convert_int('egon') # argument must be number or numeric string convert_int({'n':1}) # argument must be number or numeric string
If we want to catch all exceptions and handle them with one logic, Python provides a universal Exception type Exception
try: Detected code block except NameError: trigger NameError Processing logic corresponding to except IndexError: trigger IndexError Corresponding processing logic except Exception: Other types of exceptions are handled by the logic here
When the built-in exception is not enough, we can define the exception class by inheriting the built-in exception class
class PoolEmptyError(Exception): # You can define a new Exception by inheriting Exception def __init__(self,value='The proxy source is exhausted'): # You can customize the initialization method super(PoolEmptyError,self).__init__() self.value=value def __str__(self): # This method can be defined to customize the format of printing exception values when an exception is triggered return '< %s >' %self.value class NetworkIOError(IOError): # You can also extend a related exception based on a specific exception pass raise PoolEmptyError # __main__.PoolEmptyError: < The proxy source is exhausted > raise NetworkIOError('connection not permitted') # __ main__.NetworkIOError: connection denied
Finally, Python also provides an assertion statement assert expression, which determines that the expression expression is true. Otherwise, an exception AssertionError will be triggered, which has the same semantics as raise if not, as shown below
age='18' # If the return value of the expression isinstance(age,int) is False, an exception AssertionError is triggered assert isinstance(age,int) # Equivalent to if not isinstance(age,int): raise AssertionError
4. When to use exception handling
After understanding the except ion handling mechanism, in order to improve the fault tolerance and reliability of the program, readers may mistakenly think that try... Exception... Should be added to the program as much as possible, which is an excessive consumption of the readability of the program, because try... Exception is originally an additional logic you attach to the program, which has little to do with your main work.
If the condition of error occurrence is "predictable", we should use if to "prevent", as follows
age=input('input your age>>: ').strip() if age.isdigit(): # It can be predicted that int(age) will not trigger an exception only if the string age is a number, age=int(age) else: print('You must enter the number')
If the condition of the error is "unpredictable", that is, the exception must be triggered, then we should use the try... except statement to handle it. For example, when we write a function to download web content, it is normal for the network to have exceptions such as delay, and we simply can't predict the delay when the conditions are met, so we can only use the exception handling mechanism
import requests from requests.exceptions import ConnectTimeout # Import custom exceptions in requests module def get(url): try: response=requests.get(url,timeout=3)#If the download fails for more than 3 seconds, the ConnectTimeout exception will be triggered res=response.text except ConnectTimeout: print('Connection request timed out') res=None except Exception: print('Other network exceptions') res=None return res get('https://www.python.org')
Some preparatory knowledge of network programming
# 1. CS architecture and BS architecture Client<===========>Server Client software send Server software recv operating system operating system computer hardware<====Physical medium=====>computer hardware Browser<===========>Server # 2. Network communication The significance of network is cross regional data transmission=>Call it communication network=Physical link media+Internet communication protocol # 3. OSI layer 7 protocol Five layer agreement application layer Transport layer network layer data link layer physical layer Agreement: Specifies the organization format of data Format: header+Data part Process of sealing package: data header Unpacking process: turn around to obtain data #4. Five layer agreement Computer 1: Computer 2: application layer application layer Transport layer Transport layer network layer network layer data link layer data link layer physical layer <===========Interactive machine===========> physical layer 0101010101010 (source mac Address, target mac Address (source) ip Address, target ip Address data #4.1 the physical layer is responsible for sending electrical signals A set of physical layer data is called bit Simple electrical signals are meaningless and must be grouped #4.2 data link layer: ethernet protocol Regulation 1: a group of data is called a data frame Regulation 2: the data frame is divided into two parts=>head+data The header contains: source address and destination address, which is mac address Data inclusion: contains the overall content sent from the network layer Regulation 3: it is stipulated that every host connected to the Internet must have a network card, and each network card is burned with a unique address in the world when leaving the factory, which is called mac address Note: computer communication basically depends on roar, that is, the working mode of Ethernet protocol is broadcast (egon,Blood dislike) (help me buy steamed stuffed buns) #4.3 network layer: IP protocol Purpose to be achieved: Divide broadcast domain For each broadcast domain to connect to the outside, there must be a gateway to help the internal computer forward packets to the public network The gateway communicates with the outside world through routing protocol Regulation 1: a set of data is called a packet Regulation 2: the data frame is divided into two parts=>head+data The header contains: source address and destination address, which is IP address Data content: the overall content sent from the transport layer ipv4 Address: 8bit.8bit.8bit.8bit 0.0.0.0 255.255.255.255 Subnet mask: 8bit.8bit.8bit.8bit 255.255.255.0 Corresponding binary expression 11111111.11111111.11111111.00000000 A legal ipv4 Address component=ip address/subnet mask address 172.16.10.1/255.255.255.0 172.16.10.1/24 Computer 1: 172.16.10.1: 10101100.00010000.00001010.000000001 255255.255.255.0: 11111111.11111111.11111111.000000000 172.16.10.0: 10101100.00010000.00001010.000000000 Computer 2: 172.16.10.2: 10101100.00010000.00001010.000000010 255.255.255.255.0: 11111111.11111111.11111111.000000000 172.16.10.0: 10101100.00010000.00001010.000000000 Computer 1: Computer 2: application layer application layer Transport layer Transport layer network layer network layer data link layer data link layer physical layer <=========Two layer interactive machine========> physical layer 0101010101010 (source mac Address, xxxx)(source ip Address, target ip Address data (source mac Address, gateway mac Address) (172.16.10.10/24,101.100.200.11/10)data What you know in advance is each other's ip address But the underlying communication of computer is based on ethernet Ethernet protocol mac Address communication ARP: So will be able to ip Address resolution into mac address # Two computers are in the same LAN Computer 1:172.16.10.10/24 direct Computer 2:172.16.10.11/24 ARP: own ip,Opposite ip 1,Calculate the two network addresses. If they are the same, get the network address of computer 2 mac Just the address 2,Send broadcast packet Sender mac FF:FF:FF:FF:FF:FF 172.16.10.10/24 172.16.10.11/24 data # The two computers are not in the same LAN Computer 1:172.16.10.10/24 gateway Computer 2:101.100.200.11/10 ARP: own ip,Opposite ip 1,If the network addresses of the two computers are different, they should get the address of the gateway mac address 2,Send broadcast packet Sender mac FF:FF:FF:FF:FF:FF 172.16.10.10/24 172.16.10.1/24 data #4.3.1 summary****** ip address+mac address=>Identify a unique computer in the world Or: ip address=>Identify a unique computer in the world