Open hug2wisdom opened 4 years ago
最好是先继承Exception,比如 class Error(Exception) , 然后再继承 Error,比如 class TransistError(Error)。
eg:
class Error(Exception):
"""Base class for exceptions in this module."""
pass
class InputError(Error):
"""Exception raised for errors in the input.
Attributes:
expression -- input expression in which the error occurred
message -- explanation of the error
"""
def __init__(self, expression, message):
self.expression = expression
self.message = message
class TransitionError(Error):
"""Raised when an operation attempts a state transition that's not
allowed.
Attributes:
previous -- state at beginning of transition
next -- attempted new state
message -- explanation of why the specific transition is not allowed
"""
def __init__(self, previous, next, message):
self.previous = previous
self.next = next
self.message = message
A very important knowledge.
A
class
in an except clause is compatible with an exception if it is the same class or a base class thereof (but not the other way around — an except clause listing a derived class is not compatible with a base class). For example, the following code will print B, C, D in that order:Note that if the except clauses were reversed (with except B first), it would have printed B, B, B — the first matching except clause is triggered.
不同的 ecxept 是兼容的,但是有派生关系的时候,就要注意顺序。先从继承关系最下面的地方开始。
exception 是可以给参数的
还可以检测整个函数的异常
Exception handlers don’t just handle exceptions if they occur immediately in the try clause, but also if they occur inside functions that are called (even indirectly) in the try clause. For example:
如果你只是想展示异常,而不处理她,可以在 except 里面再 raise,eg: