Exception handling:
1. What is an exception:
An exception is a signal that an error has occurred,
Once the program fails, if there is no corresponding processing mechanism in the program
Then the error will generate an exception and throw it
The running of the program is also terminated
2. An exception is divided into three parts:
1. Abnormal tracking information;
2. The type of exception;
3. Abnormal value;
3, abnormal classification
1. Syntax exception:
1 Such exceptions should be corrected before program execution 2 print ( ' start.... ' ) 3 x=1 4 x+=1 5 if 6 print ( ' stop.... ' ) 7 IndexError 8 l=[ ' a ' , ' b ' ] 9 l[100 ] 10 11 KeyError 12 d={ ' a ' :1 } 13 d[ ' b ' ] 14 15 AttributeError: 16 class Foo: 17 pass 18 19 Foo.x 20 import os 21 os.aaa 22 23 24 ZeroDivisionError 25 1 / 0 26 27 28 FileNotFoundError 29 f=open('a.txt','r',encoding='utf-8') 30 31 ValueError: I/O operation on closed file. 32 f=open('a.txt','r',encoding='utf-8') 33 f.close() 34 f.readline() 35 36 ValueError: invalid literal for int() with base 10: 'aaaaa' 37 int('aaaaa') 38 39 40 TypeError 41 for i in 333: 42 pass 43 44 NameError 45 x 46 func()
2. Logical exception:
1 single branch: 2 try : 3 print ( ' start... ' ) 4 x = 1 5 y 6 l = [] 7 l[3 ] 8 d = { ' a ' : 1 } 9 d[ ' b ' ] 10 print ( ' end... ' ) 11 12 except NameError: 13 print ( ' The variable name is not defined ') 14
try-out : print ( ' start ... ' ) x = 1 and l = [] l[3] d = {'a': 1} d['b'] print('end...') except NameError: print ( ' The variable name is not defined ' ) except KeyError: print ( ' The key of the dictionary does not exist ' ) except IndexError: print ( ' The index is out of the range of the list ' ) print('other...')
1 Multiple exceptions are handled by the same piece of logic 2 try : 3 print ( ' start... ' ) 4 x = 1 5 y 6 l = [] 7 l[3 ] 8 d = { ' a ' : 1 } 9 d [ ' b ' ] 10 print ( ' end... ' ) 11 12 except (NameError,KeyError,IndexError): 13 print ( 'There is a problem with the variable name or the key of the dictionary or the index of the list! ' ) 14 15 print ( ' other... ' )
1 universal exception 2 try : 3 print ( ' start... ' ) 4 x = 1 5 y 6 l = [] 7 l[3 ] 8 d = { ' a ' : 1 } 9 d[ ' b ' ] 10 print ( ' end... ' ) 11 except Exception as e: 12 print ( ' universal exception ' ,e)