# Python exception handling
# The origin and classification of bugs
- The origin of the Bug
- The evolution of the world's first universal computer - Mark 2 (Mrrk||)
- Debug
# Common Types of Bug s
- Inadvertent Syntax Error SybtaxError
- The colon at the end is missing, such as if statement, loop statement, else clause, etc.
- The indentation is wrong, the ones that should be indented are not indented, and the ones that should not be indented are blindly indented
- Write English symbols as Chinese symbols, for example: quotation marks, colons, brackets
- When splicing strings, put strings and numbers together
- There is no variable defined, such as the variable of the while loop condition
- Mixture of "==" comparison operator and "=" assignment operator
Mistakes caused by inexperienced knowledge points
- Index out of bounds problem IndexError
copylst=[11,22,33,44] print(lst[4])
- I am not familiar with the use of the append() method
copylst=[] lst=append('A','B','C') print(lst)
Unclear problem solutions
- Use the print() function
- Use "#" to temporarily comment part of the code
copy""" @Author :frx @Time :2021/10/27 16:54 @Version :1.0 """ lst=[{'rating':[9,7,2062397],'id':'1292052','type':['crime','plot'],'title':'The Shawshank Redemption','actors':['Tim Robbins','morgan freeman']}, {'rating':[9,6,2052387],'id':'1292452','type':['love','plot'],'title':'Farewell My Concubine','actors':['Leslie Cheung','Zhang Fengyi','Gong Li','Ge You']}, {'rating':[9,5,2051887],'id':'1282452','type':['love','plot'],'title':'Forrest Gump','actors':['Tom Hanks','Robin White']},] name=input('Please enter the actor you want to query:') for item in lst: # Traversing the list item is a dictionary one after another actor_lst=item['actors'] for actor in actor_lst: if name in actor: print(name,'starred in',item['title'])
- solution:
- The first layer of for loop traverses the list to get each movie, and each movie is a dictionary, you only need to get the value in the dictionary according to the key. Take out the list of students according to the actor's key actors, use it to judge whether the name exists in the list, and finally take out the name of the movie according to the key title of the movie name, and output it
# Python's exception handling mechanism
# try...except structure
- single except structure
Passive pitfall: There is no error in the logic of the program code, but the program crashes due to user error or some "exceptional conditions"
Example: Enter two integers and perform division
copya=int(input('Please enter the first integer:')) b=int(input('Please enter the second integer:')) result=a/b print('The result is:',result)
- The solution to the problem of passive falling into the pit
- Python provides an exception handling mechanism, which can be caught immediately when an exception occurs, and then "digested" internally to allow the program to continue running
copy""" @Author :frx @Time :2021/10/27 17:21 @Version :1.0 """ try: a=int(input('Please enter the first integer:')) b=int(input('Please enter the second integer:')) result=a/b print('The result is:',result) except ZeroDivisionError: print('sorry,Divisor is not allowed to be 0') print('end of program')
copy""" @Author :frx @Time :2021/10/27 17:27 @Version :1.0 """ try: a=int(input('Please enter the first integer:')) b=int(input('Please enter the second integer:')) result=a/b print('The result is:',result) except ZeroDivisionError: print('sorry,Divisor is not allowed to be 0') except ValueError: print('Only numeric strings can be entered') print('end of program')
# try...except...else structure
- If no exception is thrown in the try block, the else block is executed, and if an exception is thrown in the try block, the except block is executed
copy""" @Author :frx @Time :2021/10/27 17:31 @Version :1.0 """ try: a = int(input('Please enter the first integer:')) b = int(input('Please enter the second integer:')) result = a / b except BaseException as e: print('error',e) else: print('Calculated as:',result)
# try...except...else...finally structure
- The finally block will be executed regardless of whether an exception occurs, and can be used to release the resources requested in the try block
copy""" @Author :frx @Time :2021/10/27 17:40 @Version :1.0 """ try: a = int(input('Please enter the first integer:')) b = int(input('Please enter the second integer:')) result = a / b except BaseException as e: print('error',e) else: print('Calculated as:',result) finally: print('Thank you for your use')
# Common types of exceptions in Python
serial number | exception type | describe |
---|---|---|
1 | ZeroDivisionError | divide (get value) by zero (so datatype) |
2 | IndexError | There is no such index (index) in the sequence |
3 | KeyError | The key does not exist in the map |
4 | NameError | Object not declared/initialized (has no properties) |
5 | SyntaxError | Python syntax error |
6 | ValueError | Invalid parameters passed in |
copy""" @Author :frx @Time :2021/10/27 17:46 @Version :1.0 """ #(1) Mathematical operations are abnormal # print(10/0) #ZeroDivisionError lst=[11,22,33,44] # print(lst[4]) #IndexError index starts from 0 dic={'name':'Zhang San','age':20} # print(dic['gender']) #KeyError # print(num) #NameError # int a=20 Grammatical errors #SyntaxError syntax error # a=int('hello') #ValueError
# traceback module
- Use the traceback module to print exception information
copy""" @Author :frx @Time :2021/10/27 17:52 @Version :1.0 """ # print(10/0) import traceback try: print('-----------------------------') print(1/0) except: traceback.print_exc()