12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

def parser( ):... # when error found... raise FormatError(42, file='spam.txt')...>>> try:... parser( )... except FormatError, X:... print 'Error at', X.file, X.line...Error at spam.txt 42In the except clause here, the variable X is assigned a reference to the instance that wasgenerated when the exception was raised. * In practice, though, this isn’t noticeablymore convenient than passing compound objects (e.g., tuples, lists, or dictionaries) asextra data with string exceptions, and may not by itself be a compelling enough reasonto warrant class-based exceptions. Here’s the string-based equivalent:>>> formatError = 'formatError'>>> def parser( ):... # when error found... raise formatError, {'line':42, 'file':'spam.txt'}...>>> try:... parser( )... except formatError, X:... print 'Error at', X['file'], X['line']...Error at spam.txt 42This time, the variable X in the except clause is assigned the dictionary of extradetails listed in the raise statement. The net effect is similar, but we don’t have tocode a class along the way. The class approach might be more convenient, however,if the exception should also have behavior. The exception class can also define methodsto be called in the handler:class FormatError:def _ _init_ _(self, line, file):self.line = lineself.file = filedef logerror(self):log = open('formaterror.txt', 'a')print >> log, 'Error at', self.file, self.linedef parser( ):raise FormatError(40, 'spam.txt')* As we’ll see in the next chapter, the raised instance object is also available generically as the second item inthe result tuple of the sys.exc_info call—a tool that returns information about the most recently raisedexception. This interface must be used if you do not list an exception name in an except clause, but still needaccess to the exception that occurred, or to any of its attached state information or methods.612 | Chapter 28: Exception Objects

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!