🤵♂️ Personal homepage: @Flyme awei Homepage
👨💻 About the author: a rising star in Python.
🐋 I hope you will give me your support 😘 Make progress together!
📝 If the article is helpful to you, please comment 💬 give the thumbs-up 👍 Collection 📂 Pay attention
Preface
Today is< CSDN21 day learning challenge >Day 15 of
I learned Python basics yesterday—— Reuse of functions and codes
today we will learn about Python's exception handling mechanism
Activity address: CSDN21 day learning challenge
Python exception handling mechanism
Python programs generally have certain requirements for input, but when the actual input does not meet the program requirements, the program may run incorrectly.
1, Origin and classification of Bub
1. Origin of bug
the evolution version of the world's first universal computer - Mark II
September 9, 1945, 3:00 p.m. Lieutenant Harper is leading her team to build a computer called the Mark II. This is not a complete electronic computer, it uses a large number of relays, an electronic mechanical device. The second world war is not over yet. Harper's team worked day and night. The machine room is an old building built during the first World War. It was a hot summer. There was no air conditioning in the room, and all the windows were open to dissipate heat.
Suddenly, Mark II crashed. The technician tried many methods, and finally found that the No. 70 relay was wrong. Harper observed the faulty relay and found a moth lying in the middle, which had been killed by the relay. She carefully took out the moth with a camera and pasted it on the "event log" with transparent tape, and noted "the first case of finding the moth"
since then, people have jokingly called computer errors bugs, and the work of finding errors is called (debug).
2. Common types of bugs
2.1 errors caused by carelessness
1. Missing the colon at the end: if loop statement, else statement, etc
2. Indentation error
3. English symbols are written as Chinese symbols
4. Combine the string str with the number
5.while loop has no variable defined
6. Comparison operator = = and assignment operator = (mixed)
age = int(input('Please enter age:')) # The return value of the input function is str type if age > 18: print('Grown up')
2.2 errors caused by unfamiliar knowledge
1.index out of range
2. List method lst.append
# Index out of range lst = [1, 2, 3, 4] # print(lst[4]) print(lst[3]) # 4 # Unskilled use of append() method lst = [] # lst = append(1, 2, 3) lst.append(1) # Only one element can be added at a time
2.3 errors caused by unclear thinking
# -*- coding: utf-8 -*- # @File : demo.py # @author: Flyme awei # @email : Flymeawei@163.com # @Time : 2022/8/15 10:22 # The basic knowledge of the problem caused by unclear thinking is not solid, practice!!! lst = [{'rating': [9.7, 2062397], 'id': '1292052', 'type': ['Crime', 'plot'], 'title': 'The Shawshank Redemption', 'actors': ['Tim·Robbins', 'morgan ·Freeman']}, {'rating': [9.6, 1528760], 'id': '1291546', 'type': ['plot', 'love', 'Same sex'], 'title': 'Farewell to my concubine', 'actors': ['Zhang Guorong', 'Zhang Fengyi', 'Gong Li', 'Ge you']}, {'rating': [9.5, 1559181], 'id': '1292720', 'type': ['plot', 'love'], 'title': 'Forrest Gump', 'actors': ['Tom·Hanks', 'Robin·White ']} ] name = input('Please enter the actor you want to query:') for item in lst: # Traversal list LST -- > {} item is a dictionary after another act_lst = item['actors'] # Get the list of value actors through the key actors in the item dictionary for actor in act_lst: # Traverse the actor list if name in actor: print(name, 'Performed', item['title'])
2.4 errors caused by passive pit dropping
Divide by zero exception
# -*- coding: utf-8 -*- # @File : demo.py # @author: Flyme awei # @email : Flymeawei@163.com # @Time : 2022/8/15 10:22 a = int(input('Please enter the first integer:')) b = int(input('Love letter, such as the second integer:')) result = a/b # Note: 0 cannot be a divisor print('The output result is::', result)
terms of settlement
# -*- coding: utf-8 -*- # @File : demo.py # @author: Flyme awei # @email : Flymeawei@163.com # @Time : 2022/8/15 10:22 try: a = int(input('Please enter the first integer:')) b = int(input('Please enter the second integer:')) result = a / b # Note: 0 cannot be a divisor print("{}except{}be equal to{}".format(a, b, result)) except ZeroDivisionError as error: print(error)
2, Exception handling
Python provides an exception handling mechanism, which can be caught immediately when an exception occurs, and then "digested" internally to let the program continue to run
1. Try exception statement
try: ... Code with possible exception ... ... except xxx(Exception type:): ... Exception handling code ... ...
# -*- coding: utf-8 -*- # @File : demo.py # @author: Flyme awei # @email : Flymeawei@163.com # @Time : 2022/8/15 10:22 try: a = int(input('Please enter the first integer:')) b = int(input('Please enter the second integer:')) result = a / b # Note: 0 cannot be a divisor print('The output result is::', result) except ZeroDivisionError: print('Sorry, divisor cannot be 0') print('Program end')
2. Multiple except statements
try: ... Code with possible exception ... ... except Exception1: ... Exception handling code ... ... except Exception2: ... Exception handling code ... ... except BaseException: ... Exception handling code ... ...
# -*- coding: utf-8 -*- # @File : demo.py # @author: Flyme awei # @email : Flymeawei@163.com # @Time : 2022/8/15 10:22 try: a = int(input('Please enter the first integer:')) b = int(input('Please enter the second integer:')) result = a / b # Note: 0 cannot be a divisor print('The output result is::', result) except ZeroDivisionError: print('Sorry, divisor cannot be 0') except ValueError: print('Sorry, only numeric string can be entered') print('Program end')
Normal output:
Exception except zero: ZeroDivisionError
Value error: ValueError
3. Try except else structure
If no exception is thrown in try, the else block is executed; If an exception is thrown in try, the exception block is executed, and the else block is not executed.
# -*- coding: utf-8 -*- # @File : demo.py # @author: Flyme awei # @email : Flymeawei@163.com # @Time : 2022/8/15 10:22 # If no exception is thrown in the try, the else block is executed; if an exception is thrown in the try, the exception block is executed try: a = int(input('Please enter the first integer:')) b = int(input('Love letter, such as the second integer:')) result = a / b # Note: 0 cannot be a divisor except BaseException as e: print('Error ', e) else: print('The calculation result is:', result)
4. Try except else finally structure
finally is executed regardless of whether an exception occurs. It is often used to explain the resources applied in the try block
# -*- coding: utf-8 -*- # @File : demo.py # @author: Flyme awei # @email : Flymeawei@163.com # @Time : 2022/8/15 10:22 ''' try except else finally structure finally Whether or not an exception occurs, it will be executed and can often be used to explain try Resources requested in the block ''' 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('The result is::', result) finally: print('Thank you for your use') print('Program end')
5.traceback module
Print exception information using traceback module
# -*- coding: utf-8 -*- # @File: 8.trackback module.py # @author: Flyme awei # @email : Flymeawei@163.com # @Time : 2022/8/15 16:01 import traceback try: print(520) print(1 / 0) except: traceback.print_exc()
3, Python common exception types
abnormal | describe |
---|---|
ZeroDivisionError | Divide by zero exception |
IndexError | There is no secondary index in the list note: the index starts from zero |
KeyError | The key dic['key '] does not exist in the map |
NaneError | Object not declared / initialized (no properties) |
SyntaxError | Python syntax error |
ValueError | Invalid parameter passed in |
4, PyCharm program debugging
Let's take a look at the code:
# -*- coding: utf-8 -*- # @File: debugging of pycharm program.py # @author: Flyme awei # @email : Flymeawei@163.com # @Time : 2022/8/15 16:46 i = 1 while i < 2: print(i)
1. Breakpoint
When the program runs here, temporarily suspend and stop execution. At this time, you can observe the operation of the program in detail to facilitate further judgment.
2. Commissioning
There are three ways to enter the debug view:
(1) Click the button on the toolbar
(2) Right click the edit area: Click: debug 'module name'
(3) Shortcut key: shift+F9
5, Summary
Python common exception types
abnormal | describe |
---|---|
ZeroDivisionError | Divide by zero exception |
IndexError | There is no secondary index in the list note: the index starts from zero |
KeyError | The key dic['key '] does not exist in the map |
NaneError | Object not declared / initialized (no properties) |
SyntaxError | Python syntax error |
ValueError | Invalid parameter passed in |