程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Complete Python exception handling in ten minutes

編輯:Python

exception handling :

Capture exception , Simple catch exception syntax , In program development , You can try to add try To catch exceptions

try:
Code to try to execute
except:
Wrong handling 

try Try Fill in the password you want to try below , Code that is not sure whether it will execute properly

except If not , Fill in the failure code below

Example : Simple exception capture drill – User is required to enter an integer

try:
# Not sure what code you're trying to execute
# Prompt user for a number
num = int(input(" Please enter a number :"))
except:
print(" Please enter a correct number !")
print("-"*50)

Error type capture :

When the program is executed , You may encounter different types of , And you need to target different types of exceptions , Respond differently , At this point, you need to specify the error type

try:
# Code to try to execute
pass
except Wrong type 1:
# For the type of error 1, Corresponding code handling
pass
except( Wrong type 2, Wrong type 3):
# For the type of error 2 and 3 Corresponding code handling
pass
except Exception as result:
print(" Unknown error %s" %result)

Sample requirements :

Prompt the user to enter an integer

Use 8 Divide by the integer entered by the user and output

while True:
try:
# Prompt the user to enter an integer
num = int(input(" Enter an integer :"))
# If the input is not an integer, an error will be reported , Input 0 It's also a mistake , Here we need to catch exceptions The first word with wrong assignment is treated as a keyword
result = 8 / num
print(result)
except ZeroDivisionError:
print(" Mathematical error ")
except ValueError:
print(" Please enter a number ")

Catch unknown error :

except Exception as result:
print(" Unknown error %s" %result)

Unknown errors can be output to the console , Instead of reporting an error and crashing Exception keyword

try:
# Prompt the user to enter an integer
num = int(input(" Enter an integer :"))
# If the input is not an integer, an error will be reported , Input 0 It's also a mistake , Here we need to catch exceptions The first word with wrong assignment is treated as a keyword
result = 8 / num
print(result)
except ValueError:
print(" Please enter a number ")
except Exception as result:
print(" Unknown error %s"%result)

Complete syntax for exception capture :

try:
# Code to try to execute
pass
except Wrong type 1 The first keyword of :
# For the type of error 1 Corresponding code handling
pass
except Wrong type 2 First keyword of :
# For the type of error 2 Corresponding code processing of
pass
except ( Wrong type 3, Wrong type 4):
# For the type of error 3,4 Corresponding code processing of
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(" Whether or not there are exceptions , Code that will execute ")

Sample code :

try:
# Prompt the user to enter an integer
num = int(input(" Enter an integer :"))
# If the input is not an integer, an error will be reported , Input 0 It's also a mistake , Here we need to catch exceptions The first word with wrong assignment is treated as a keyword
result = 8 / num
print(result)
except ValueError:
print(" Please enter a number ")
except Exception as result:
print(" Unknown error %s" % result)
else:
print(" Try to succeed !")
finally:
print(" Code that executes regardless of whether an error occurs ")
print("==="*20)

The transmission of exceptions :

Function as / When an exception occurs in method execution , The exception is passed to the function / The caller of the method

If passed to the main program , Still no exception handling , The program will be terminated

So , You only need to do an exception handling in the main program to complete the exception handling of the code

Sample code :

def demo1():
return int(input(" Input 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(" The program appears %s error "%(result))

Throw out raise abnormal :

Actively throw an exception

python One is provided in Exception Exception class

At development time , If you meet the needs of a particular business , Hope to throw an exception , Sure

Create a Exception The object of

Use raise Keyword throws an exception object

Demand case :

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
result =input(" Please input a password ")
#2. Determine password length >=8 , Return the password entered by the user
if len(result) >=8:
return result
#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> Actively throw an exception
raise ex
# Prompt user for password
try:
print(input_password())
except Exception as result:
print(result)

The above is python All all exception handling , It's a little bit easier !

Recommended reading

  • 5 Life saving python Tips

  • Thousands of Python Class library , It's so cool !

  • 10 That's ok Python What interesting things code can do ?


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved