Reasonable use of exceptions in the programming process can make the program execute normally . It has the form of throwing an exception directly , It can also be added to the business logic processing of exceptions by capturing exceptions .
【 Read the whole passage 】
Create a custom exception class case
class MyException(Exception):
def __init__(self, msg):
'''
:param msg: Abnormal information
'''
self.msg = msg
Use raise Keyword throw exception case
raise Keyword throws an exception mainly for the specific condition .
def throw_exception(num=0):
'''
Test the exception throwing function
:param num: The number
:return:
'''
if num == 10:
raise MyException('num Can not be equal to 10')
else:
print(' At present num=',num)
throw_exception(10)
Calling throw_exception After the function , The incoming value is 10 The following exception is thrown .
# raise MyException('num Can not be equal to 10')
# __main__.MyException: num Can not be equal to 10
Use try...except Capture exception cases
Use try Keyword catch exception , You can add your own business processing logic to the exception processing so that the exception will not be thrown directly .
def catch_exception(num=0):
'''
Test the exception handler
:param num: The number
:return:
'''
try:
throw_exception(num)
except MyException as e:
print(' Enter exception handling : At present num=',num)
catch_exception(10)
call catch_exception Function after exception handling , Instead of throwing exceptions, normal business processing is performed , Deal with it according to our expected plan .
# Enter exception handling : At present num= 10
【 Past highlights 】
python Local music player production process ( Complete source code attached )
Automation tools :PyAutoGUI Mouse and keyboard control , A sharp weapon for freeing hands !
Have you ever seen a birthday cake from a programming ape ?
Lazy man python operation , You always need to import only one library into your code ...
Office automation : Mobile number extractor , Use regular expressions to easily extract mobile phone numbers from text files ...