| Exception name | Description |
|---|---|
| BaseException | The base class of all exceptions |
| SystemExit | Parser request to exit |
| Exception | Base class for general errors |
| StopIteration | Iterator has no more values |
| ArithmeticError | The base class for all numerical calculation errors |
| FloatingPointError | Floating point calculation error |
| OverflowError | Numerical operation exceeds the maximum limit |
| AttributeError | Object does not have this attribute |
| FileNotFoundError | File not found |
| ZeroDivisionError | Division (or modulo) zero (all data types) |
| ....... | ...... |
grammar
try:
Code where the error may occur
except:
Code executed if an exception occurs
note:
Catch multiple specified exceptions
When catching multiple exceptions, you can put the name of the exception type to be caught after except, and write it in a tuple.
try:. print(1/0) except (NameError, ZeroDivisionError): print('There is an error')
Capture exception description information
try: print(num) except (NameError, ZeroDivisionError) as result: print(result)
Catch all exceptions
Exception is the parent class of all program exception classes.
try: print(num) except Exception as result: print(result)
Abnormal else
Else means the code to be executed if there is no exception
try: print(1) except Exception as result: print(result) else: print('I am else, the code executed when there is no exception')
Abnormal finally
Finally represents the code to be executed regardless of whether it is abnormal, such as closing a file.
try: f = open('test.txt','r') except Exception as result: f = open('test.txt','w') else: print('No exception, really happy') finally: f .close()
Experience abnormal delivery
import time
try:
f =open('test.txt')try:while True:
content = f.readline()iflen(content)==0:break
time.sleep(2)print(content)
except:
# If an exception occurs in the process of reading the file, then it will be caught
# For example, press ctrl+c
print('Unexpected termination of reading data')finally:
f.close()print('Close file')
except:print("No such file")
In Python, the syntax for throwing custom exceptions is raise exception class objects.
# Custom exception class, inherit Exception
classShortInputError(Exception):
def __init__(self, length, min_len):
self.length = length
self.min_len = min_len
# Set the description of the exception thrown
def __str__(self):return f'The length you entered is{self.length},Not less than{self.min_len}Characters'
def main():try:
con =input('Please enter your password:')iflen(con)<3:
raise ShortInputError(len(con),3)
except Exception as result:print(result)else:print('The password has been entered')main()