Python-Exception Handling

One, understand the exception###


Two, Python exception classification###


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)
....... ......

Three, exception handling


grammar

try:
  Code where the error may occur
except: 
  Code executed if an exception occurs

note:

  1. If the exception type of the code you are trying to execute is inconsistent with the exception type to be caught, the exception cannot be caught
  2. Generally, only one line of code to be executed is placed under try

Fourth, abnormal transmission


Experience abnormal delivery

  1. Try to open the test.txt file in read-only mode. If the file exists, read the content of the file, and prompt the user if the file does not exist.
  2. Requirements for reading content: Try to read the content in a loop. If the user accidentally terminates the program is detected during the reading process, the except captures the exception.
    Often and prompt the user
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")

Five, custom exception

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()

Recommended Posts

Python-Exception Handling
Python exception handling