预计阅读本页时间:-
Providing Exception Methods
Besides enabling application-specific state information, custom constructors also better support extra behavior for exception objects. That is, the exception class can also define methods to be called in the handler. The following, for example, adds a method that uses exception state information to log errors to a file:
class FormatError(Exception):
logfile = 'formaterror.txt'
def __init__(self, line, file):
self.line = line
self.file = file
def logerror(self):
log = open(self.logfile, 'a')
print('Error at', self.file, self.line, file=log)
def parser():
raise FormatError(40, 'spam.txt')
try:
parser()
except FormatError as exc:
exc.logerror()
广告:个人专属 VPN,独立 IP,无限流量,多机房切换,还可以屏蔽广告和恶意软件,每月最低仅 5 美元
When run, this script writes its error message to a file in response to method calls in the exception handler:
C:\misc> C:\Python30\python parse.py
C:\misc> type formaterror.txt
Error at spam.txt 40
In such a class, methods (like logerror) may also be inherited from superclasses, and instance attributes (like line and file) provide a place to save state information that provides extra context for use in later method calls. Moreover, exception classes are free to customize and extend inherited behavior. In other words, because they are defined with classes, all the benefits of OOP that we studied in Part VI are available for use with exceptions in Python.
[78] As suggested earlier, the raised instance object is also available generically as the second item in the result tuple of the sys.exc_info() call—a tool that returns information about the most recently raised exception. This interface must be used if you do not list an exception name in an except clause but still need access to the exception that occurred, or to any of its attached state information or methods. More on sys.exc_info in the next chapter.