current position：Home>Python notes (22): errors and exceptions
Python notes (22): errors and exceptions
2022-01-30 16:49:49 【A bowl week】
Little knowledge , Great challenge ！ This article is participating in “ A programmer must have a little knowledge ” Creative activities .
Hello everyone , I am a A bowl week , One doesn't want to be drunk ( Internal volume ) The front end of the . If you are lucky enough to get your favor , I'm very lucky ~
In daily learning Python In the process , Due to its limited programming level , It really hurts me to throw an exception to me from time to time ; Found in the process of learning Python Errors in can be divided into syntax errors and exceptions .
Python Grammatical errors in are usually the most obvious errors , Because the code is not written as required , It is often prone to grammatical errors
>>> print("hello world) File "<stdin>", line 1 print("hello world) ^ SyntaxError: EOL while scanning string literal >>> while True print("hello world") File "<stdin>", line 1 while True print("hello world") ^ SyntaxError: invalid syntax Copy code
Python The syntax interpreter will find out where the error occurs first , And mark a small arrow below it
What is an anomaly ？ An exception is an event , This event will occur while the program is running , Affect the normal execution of the program ; because Python in Everything is object , So the exception is also an object , It means an error ; In general, even if Python The grammar is correct , When it's running , There is also the possibility of mistakes , Errors detected during runtime are called exceptions .
>>> print(1 / 0) # 0 Not as a divisor , An exception Traceback (most recent call last): File "<stdin>", line 1, in <module> ZeroDivisionError: division by zero >>> print(my_name) # # my_name Undefined , An exception Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'my_name' is not defined >>> print("5" + 5) # # int Cannot be associated with str Add up , An exception Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: can only concatenate str (not "int") to str Copy code
Different exceptions will prompt different error messages , The first part of the error message shows the context in which the exception occurred , And display the specific information in the form of call stack .
At the end of the article, all the common error messages are sorted out Portal
When Python When an exception occurs in the script, we don't catch and handle it in time , The program will terminate execution .python Use in
try/except Statement can handle exceptions well .
try: print(my_name) # No definition my_nama Variable , An exception will occur print(" I am the result of normal execution ") # If the program is normal, it will execute this code except NameError: print(" If something unusual happens , Will execute me ") # If an error occurs, this code will be executed Copy code
Execute the process ：
- Executive execution try Clause （ In keywords try And keywords except The sentence between ）
- Variable not found , trigger NameError error
- The exception type is exactly the same as except The following statements are consistent with , Ought to be except Clause will be executed
Be careful ： If the exception does not match it , Still throw exceptions
If you want one except Clause can handle multiple exceptions at the same time , These exceptions will be placed in parentheses as a tuple , for example :
try: pass except (RuntimeError, TypeError, NameError): pass Copy code
try A statement can also contain multiple
except Clause , To handle different specific exceptions . At most one branch will be executed .
the last one except Clause to ignore the name of the exception , It will be used as a wildcard . Can pass
raise Throw an exception
while True: try: a = int(input(" Please enter the dividend ：")) b = int(input(" Please enter the dividend ：")) c = a / b print(" The result is ：", c) break # Out of the loop except ValueError: print(" The input is not a number , Please re-enter ") except: print(" Unknown exception ") raise # If not ValueError, Will print the previous statement and throw an exception Copy code
Execute the process
try/except There is also an optional
else Clause , Want to use this clause , It must be placed in all
except After Clause .
else Clause will be
try Clause is executed when no exception occurs .
Execute the process
Sample code ：
while True: try: a = int(input(" Please enter the dividend ：")) b = int(input(" Please enter the dividend ：")) except ValueError: print(" The input is not a number , Please re-enter ") except ZeroDivisionError: print(" The divisor is 0") else: c = a / b print(" The result is ：", c) print(' Calculation completed ') break Copy code
There is a small problem here , If in an endless loop statement ,
breakkeyword , They don't execute
Use else Clause is better than putting all statements in
try The clause is better , This can avoid some unexpected , and
except An exception that can't be caught .
try-finally Statement will execute the last code whether or not an exception occurs .
while True: try: a = int(input(" Please enter the dividend ：")) b = int(input(" Please enter the dividend ：")) except ValueError: print(" The input is not a number , Please re-enter ") except ZeroDivisionError: print(" The divisor is 0") else: c = a / b print(" The result is ：", c) print(' Calculation completed ') break finally: print(" The program is finished ") # this sentence , Whether or not an exception occurs, it will execute Copy code
Throw an exception
raise Statement throws a specified exception
raise [Exception [, args [, traceback]]] Copy code
Exception It's the type of exception （ for example ,
NameError） Any of the parameter standard exceptions
args It is an exception parameter provided by itself （ Optional ）.
tracebackargs It's tracking exception objects （ Optional ）.
x = int(input()) # Get a number if x == 0: # If it is equal to 0 Throw out Exception abnormal raise Exception('x be equal to 0.') # Exception: x be equal to 0. Copy code
The previous code has a bug, The divisor is 0 Throw an exception directly , A solution in this way
while True: try: a = int(input(" Please enter the dividend ：")) b = int(input(" Please enter the dividend ：")) if b == 0: raise ZeroDivisionError(' The divisor is equal to 0.') except ValueError as e: # Pass exception information to e print(e) # Print out the exception information print(" The input is not a number , Please re-enter ") except ZeroDivisionError: print(" The divisor is 0") else: c = a / b print(" The result is ：", c) print(' Calculation completed ') break finally: print(" The program is finished ") # this sentence , Whether or not an exception occurs, it will execute Copy code
dxcept...as...You can pass exception information
User defined exception
You can have your own exceptions by creating a new exception class . Exception classes inherit from Exception class , Can inherit directly , Or indirectly
# Customize an exception class class MyError(Exception): # Exception classes inherit from Exception class """ An exception class defined by yourself """ def __init__(self, message): self.message = message raise MyError(" An exception class defined by yourself ") Copy code
author[A bowl week],Please bring the original link to reprint, thank you.
The sidebar is recommended
- Python notes (6): definition and use of lists
- Python notes (V): string operation
- Python notes (IV): use of functions and modules
- Python notes (3): conditional statements and circular statements
- Python notes (II): lexical structure
- Notes on python (I): getting to know Python
- [Python data structure series] - tree and binary tree - basic knowledge - knowledge point explanation + code implementation
- [Python daily homework] Day7: how to combine two dictionaries in an expression?
- How to implement a custom list or dictionary in Python
- 15 advanced Python tips for experienced programmers
guess what you like
Python string method tutorial - how to use the find() and replace() functions on Python strings
Python computer network basics
Python crawler series: crawling global airport information
Python crawler series: crawling global port information
How to calculate unique values using pandas groupby
Application of built-in distribution of Monte Carlo simulation SciPy with Python
Gradient lifting method and its implementation in Python
Pandas: how to group and calculate by index
Can you create an empty pandas data frame and fill it in?
Python basic exercises teaching! can't? (practice makes perfect)
- Exploratory data analysis (EDA) in Python using SQL and Seaborn (SNS).
- Turn audio into shareable video with Python and ffmpeg
- Using rbind in python (equivalent to R)
- Pandas: how to create an empty data frame with column names
- Talk about quantifying investment using Python
- Python, image restoration in opencv - CV2 inpaint
- Python notes (14): advanced technologies such as object-oriented programming
- Python notes (13): operations such as object-oriented programming
- Python notes (12): inheritance such as object-oriented programming
- Chapter 2: Fundamentals of python-5 Boolean
- Python notes (11): encapsulation such as object-oriented programming
- Python notes (10): concepts such as object-oriented programming
- Gradient lifting method and its implementation in Python
- Van * Python | simple crawling of a site course
- Chapter 1 preliminary knowledge of pandas (list derivation and conditional assignment, anonymous function and map method, zip object and enumerate method, NP basis)
- Nanny tutorial! Build VIM into an IDE (Python)
- Fourier transform of Python OpenCV image processing, lesson 52
- Introduction to python (III) network request and analysis
- China Merchants Bank credit card number recognition project (Part I), python OpenCV image processing journey, Part 53
- Introduction to python (IV) dynamic web page analysis and capture
- Python practice - capture 58 rental information and store it in MySQL database
- leetcode 119. Pascal's Triangle II（python）
- leetcode 31. Next Permutation（python）
- [algorithm learning] 807 Maintain the city skyline (Java / C / C + + / Python / go / trust)
- The rich woman's best friend asked me to write her a Taobao double 11 rush purchase script in Python, which can only be arranged
- Glom module of Python data analysis module (1)
- Python crawler actual combat, requests module, python realizes the full set of skin to capture the glory of the king
- Summarize some common mistakes of novices in Python development
- Python libraries you may not know
- [Python crawler] detailed explanation of selenium from introduction to actual combat 
- This is what you should do to quickly create a list in Python
- On the 55th day of the journey, python opencv perspective transformation front knowledge contour coordinate points
- Python OpenCV image area contour mark, which can be used to frame various small notes
- How to set up an asgi Django application with Postgres, nginx and uvicorn on Ubuntu 20.04
- Initial Python tuple
- Introduction to Python urllib module
- Advanced Python Basics: from functions to advanced magic methods
- Python Foundation: data structure summary
- Python Basics: from variables to exception handling
- Python notes (22): time module and calendar module