current position:Home>[learning notes] Python exception handling try except...

[learning notes] Python exception handling try except...

2022-01-29 16:23:18 Broken wind Bosco

Let's start with the complete code for exception handling :

try:
    # Code to try to execute 
except  Wrong type 1:
    #  For the type of error 1, Corresponding code handling 
    pass
except  Wrong type 2:
    #  For the type of error 2, Corresponding code handling 
    pass
except  Wrong type 3 :
    #  For the type of error 3, Corresponding code handling 
    pass
except Exception as result:
    #  Print error messages 
    print(result)
else:
    #  Code that will execute without exception 
    pass
finally:
    #  No matter whether there is any abnormality , Code that will execute 
    print(" No matter whether there is any abnormality , Code that will execute ")
 Copy code 

In certain circumstances , We can't completely define all errors, so we introduce Exception Handle

try:
    num = int(input(" Please enter an integer :"))
    print(num/num)
# except ZeroDivisionError:
# print(" Please enter a correct integer , Can't divide 0:")
    #  You can write exception handling methods for error types 
except ValueError:
    print(" Please enter a number , You cannot enter letters or Chinese characters ")
except Exception as  result:
    print(" Unknown error  %s" % result)
 Copy code 

Exception handling

  • The transmission of exceptions -- When function / Method perform Something unusual happened , Meeting Pass exception to function / Method Of Calling party
  • If Pass to main program , still No exception handling , The program will be terminated

Tips

  • In development , You can add the operation of catching exceptions in the main function
  • Other functions called in the main function China , As long as there is an exception , Will be passed to the main function Exception trapping in
  • So you don't have to be in the code , A large increase in Exception trapping , Keep the code clean

demand

  1. Defined function demo1() Prompts the user to enter an integer and returns
  2. Defined function demo2() call demo1
  3. Call in main program demo2
def demo1():
    return int(input(" Please enter an integer :"))

def demo2():
    return demo1()

#  Take advantage of the transitivity of exceptions , Catch exception in main program 
try:
    print(demo2())
except Exception as result:
    print(" Unknown error  %s" % result)
 Copy code 

Actively throw an exception

Actively throw an exception
  • stay Python One is provided in Exception Exception class
  • At development time , If meet Specific business requirements , hope Throw an exception , Sure :
    • Create a Exception The object of
    • Use raise keyword Throw out Exception object
demand
  • Definition input_password function , Prompt user for password
  • If the user enters the length < 8, Throw an exception
  • If the user enters the length >= 8 , Return the password entered
def input_password():
    # 1.  Prompt user for password 
    pwd = input(" Please input a password :")
    # 2.  Determine password length  >= 8, Return the password entered by the user 
    if len(pwd) >= 8:
        return pwd
    # 3.  If  < 8  Actively throw an exception 
    print(" Actively throw an exception ")
    # 1>  Create exception object  -  You can use the error message string as an argument 
    ex = Exception(" Insufficient password length ")
    # 2>  Throw an exception 
    raise ex
#  Prompt user for password 
try:
    print(input_password())
except Exception as result:
    print(result)
 Copy code 

copyright notice
author[Broken wind Bosco],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/01/202201291623158212.html

Random recommended