|
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!'
?????п???????κ????????п??????????????????????????????????м?????????????????????????????????????′?????????????????????????????????????????????????鶨?????????????????????????????????????????????
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 ??侭?? break ?? return ????????????finally ???
??finally ????е????????????????????????????????????????????Щ???????????????á?
?? try ????п?????????? except ??????? finally ??????????????檔
|
Python ??? |
|
????? 7. ???????? ????? Python ??? ??? 9. ??
Release 2.3, documentation updated on July 29, 2003.
See About this document... for information on suggesting changes. ?????, @ssv