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

Python custom exception /raise keyword throws an exception

編輯:Python

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


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