|
Python ??? |
|
????? 7. ???????? ????? Python ??? ??? 9. ??
????
???????????????????????????????????????????????????????????????????????Python??????????????????????????? syntax errors and exceptions????
???????????????????????????Python?????????????????
>>> while True print 'Hello world' File "<stdin>", line 1, in ? while True print 'Hello world' ^ SyntaxError: invalid syntax
??????????????????????????????????????????????????????????????????????????????????????????????????print???????????????????e???:???????????????????????????????????????????????????????
????????????????????????????????????????????????????????????????????????????????????????????????????????????Python???????????????????????????????????????????????????
>>> 10 * (1/0) Traceback (most recent call last): File "<stdin>", line 1, in ? ZeroDivisionError: integer division or modulo by zero >>> 4 + spam*3 Traceback (most recent call last): File "<stdin>", line 1, in ? NameError: name 'spam' is not defined >>> '2' + 2 Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: cannot concatenate 'str' and 'int' objects
????????????????????????????????????????????????????????????????????????????????????????????? ZeroDivisionError ???????????? NameError??????????? TypeError ???????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????
??????????????????????????????????????????????????????????
?????????????????????????????????????????????????????????????????????????????????????
Python ?????? ???????????????????^
??????????????????????????????????????????????????????????????????????????????????????????????????????? Control-C ????????????????????????????????????????????????????? KeyboardInterrupt ????
>>> while True: ... try: ... x = int(raw_input("Please enter a number: ")) ... break ... except ValueError: ... print "Oops! That was no valid number. Try again..." ...
try ??????????????
???????? try ???????try ?? except???????????????
??????????????except ??? ??try???????????????????
?????try???????????????????????????????????????????????????except????????????????????????????except???????try??????????????????????try??????????
??????????????????except????????????????????????????????try?????????????????????????????????????????????????????????????????????
???try ???????????? except ????????????????????????????????????????? ??????????????????try???????????????????try????????????????????????????????except???????????????????????????????
... except (RuntimeError, TypeError, NameError): ... pass
??????except??????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????
import string, sys try: f = open('myfile.txt') s = f.readline() i = int(string.strip(s)) except IOError, (errno, strerror): print "I/O error(%s): %s" % (errno, strerror) except ValueError: print "Could not convert data to an integer." except: print "Unexpected error:", sys.exc_info()[0] raise
try ... except ???????????? else ????? ?????????????????except????????try?????????????????????????????????????????
for arg in sys.argv[1:]: try: f = open(arg, 'r') except IOError: print 'cannot open', arg else: print arg, 'has', len(f.readlines()), 'lines' f.close()
??? else ?????? try ???????????????????????????? try ... except ???????????????????????????????????????
???????????????????????????????????????????????????????????????????????????????
???????????????????? except
?????????????????????????????????????????
instance.args
?????????????????????????????
__getitem__
?? __str__
??????????????????????????????????? .args??
>>> try: ... raise Exception('spam', 'eggs') ... except Exception, inst: ... print type(inst) # the exception instance ... print inst.args # arguments stored in .args ... print inst # __str__ allows args to printed directly ... x, y = inst # __getitem__ allows args to be unpacked directly ... print 'x =', x ... print 'y =', y ... <type 'instance'> ('spam', 'eggs') ('spam', 'eggs') x = spam y = eggs
?????????????????????????????????????????????????????????“???”???????????
??????????????????????????try??????????????????????????????????????????????????????????????
>>> def this_fails(): ... x = 1/0 ... >>> try: ... this_fails() ... except ZeroDivisionError, detail: ... print 'Handling run-time error:', detail ... Handling run-time error: integer division or modulo
???????????????????????????? raise ????????????????
>>> raise NameError, 'HiThere' Traceback (most recent call last): File "<stdin>", line 1, in ? NameError: HiThere
???????????????????????????????????????????????
????????????????????????????raise ???????????????????????????
>>> try: ... raise NameError, 'HiThere' ... except NameError: ... print 'An exception flew by!' ... raise ... An exception flew by! Traceback (most recent call last): File "<stdin>", line 2, in ? NameError: HiThere
????????????????????????????????????????????????????????? Exception ???????????
>>> class MyError(Exception): ... def __init__(self, value): ... self.value = value ... def __str__(self): ... return repr(self.value) ... >>> try: ... raise MyError(2*2) ... except MyError, e: ... print 'My exception occurred, value:', e.value ... My exception occurred, value: 4 >>> raise MyError, 'oops!' Traceback (most recent call last): File "<stdin>", line 1, in ? __main__.MyError: 'oops!'
????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????E?????????????????????????????????????????????
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
????????????????????????????“Error”????
??????????????????????????????????????????????????????????????????????????????? 9??“??”??
try ???????????????????????????????????????????????????
>>> try: ... raise KeyboardInterrupt ... finally: ... print 'Goodbye, world!' ... Goodbye, world! Traceback (most recent call last): File "<stdin>", line 2, in ? KeyboardInterrupt
????try???????????????? finally ??????????????????????????finally?????????????????????? try ??B?? break ?? return ????????????finally ???
??finally ????????????????????????????????????????????????????????????????
?? try ?????????????? except ??????? finally ??????????????n
|
Python ??? |
|
????? 7. ???????? ????? Python ??? ??? 9. ??
Release 2.3, documentation updated on July 29, 2003.
See About this document... for information on suggesting changes. ?????, @ssv