try: text = input('Enter something --> ') except EOFError: print('Why did you do an EOF on me?') except KeyboardInterrupt: print('You cancelled the operation.') else: print('You entered {0}'.format(text))
输出
1 2 3 4 5 6 7 8 9 10 11
$ python try_except.py Enter something --> # Press ctrl-d Why did you do an EOF on me?
$ python try_except.py Enter something --> # Press ctrl-c You cancelled the operation.
$ python try_except.py Enter something --> no exceptions You entered no exceptions
try: text = input('Enter something --> ') iflen(text) < 3: raise ShortInputException(len(text), 3) # Other work can continue as usual here except EOFError: print('Why did you do an EOF on me?') except ShortInputException as ex: print('ShortInputException: The input was {0} long, expected at least {1}'\ .format(ex.length, ex.atleast)) else: print('No exception was raised.')
输出
1 2 3 4 5 6 7
$ python raising.py Enter something --> a ShortInputException: The input was 1 long, expected at least 3
$ python raising.py Enter something --> abc No exception was raised.
assert
和很多编程语言一样,Python 有一个assert语句。这是它的用法。
1 2 3 4 5 6 7 8 9
>>> assert1 + 1 == 2 >>> assert1 + 1 == 3 Traceback (most recent call last): File "<stdin>", line 1, in <module> AssertionError >>> assert2 + 2 == 5, "Only for very large values of 2" Traceback (most recent call last): File "<stdin>", line 1, in <module> AssertionError: Only for very large values of 2
try: f = open('poem.txt') whileTrue: # our usual file-reading idiom line = f.readline() iflen(line) == 0: break print(line, end='') time.sleep(2) # To make sure it runs for a while except KeyboardInterrupt: print('!! You cancelled the reading from the file.') finally: f.close() print('(Cleaning up: Closed the file)')
输出
1 2 3 4 5 6
$ python finally.py Programming is fun When the work is done if you wanna make your work also fun: !! You cancelled the reading from the file. (Cleaning up: Closed the file)