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

Python | exception inheritance relationship and custom exception implementation code examples

編輯:Python

Custom exception classes should always inherit from built-in Exception class , Or inherited from those that are themselves from Exception Inherited class . Although all classes also inherit from BaseException , But you should not use this base class to define new exceptions .BaseException Reserved for system exit exceptions , such as KeyboardInterrupt or SystemExit And other exceptions that signal the application to exit . therefore , Catching these exceptions doesn't make sense in itself . In this case , If you inherit BaseException It may cause your custom exception not to be caught and directly send a signal to exit the program .

Patients with a :

# Custom exception
# Custom exceptions can make exceptions more accurate
# Custom exception classes : When list Inner element length exceeds 10 Throw an exception when
# Custom exception classes : The message is less than 8 Throw an exception when 
class lenError(Exception):
def __init__(self,msg):
self.msg = msg
def __str__(self):
return self.msg
lst = [1,2,3,4,5,6,7]
try :
if not 8 <= len(lst) <= 10:
raise lenError(" The length is not 8 To 10 Between ")
except lenError as er:
print(er)

Example 2 :

 Custom exception Need to inherit Exception
class MyException(Exception):
def __init__(self, *args):
self.args = args
#raise MyException(' Let's make an exception ')
# Common practice is to define exception base classes , Then derive different types of exceptions
class loginError(MyException):
def __init__(self, code = 100, message = ' Login exception ', args = (' Login exception ',)):
self.args = args
self.message = message
self.code = code
class loginoutError(MyException):
def __init__(self):
self.args = (' Exit exception ',)
self.message = ' Exit exception '
self.code = 200
#raise loginError() # Here comes a sudden return raise The exception thrown will break the program
#
try:
raise loginError()
except loginError as e:
print(e) # Abnormal output
print(e.code) # Output error code
print(e.message)# Output error message 

 . How to throw an exception manually :raise

The system's own exception will be thrown automatically as long as it is triggered , such as NameError, However, user-defined exceptions require the user to decide when to throw them . raise The only parameter that specifies the exception to be thrown . It must be an exception instance or an exception class ( That is to say Exception Subclasses of ). Most of the names of exceptions are "Error" ending , Therefore, the actual naming should be the same as the standard exception naming .


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