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