常见错误:
>>> print 'hello' #试图使用Python2的语法产生SyntaxError
File "<stdin>", line 1
print 'hello'
^
SyntaxError: Missing parentheses in call to 'print'
>>> print('hello') #首行多打了一个空格产生IndentationError
File "<stdin>", line 1
print('hello')
^
IndentationError: unexpected indent
>>> print(undefined) #试图访问未定意思的变量产生NameError
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'undefined' is not defined
>>> print(1 + 'wow')#操作或函数应用于不适当的对象产生TypeError
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>>
处理异常:
>>> def get_number():
... "Returns a float number"
... number = float(input("Enter a float number: "))
... return number
...
>>>
>>> while True:
... try:
... print(get_number())
... except ValueError:
... print("You entered a wrong value.")
...
Enter a float number: 45.0
45.0
Enter a float number: 24,0
You entered a wrong value.
Enter a float number: Traceback (most recent call last):
File "<stdin>", line 3, in <module>
File "<stdin>", line 3, in get_number
KeyboardInterrupt
首先输入了一个合适的浮点值,解释器返回输出这个值。
然后输入以逗号分隔的值,抛出 ValueError
异常,except
子句捕获,并且打印出错误信息。
第三次按下 Ctrl + C
,导致了 KeyboardInterrupt
异常发生,这个异常并未在 except 块中捕获,因此程序执行被中止。
一个空的 except
语句能捕获任何异常。
>>> try:
... input() # 输入的时候按下 Ctrl + C 产生 KeyboardInterrupt
... except:
... print("Unknown Exception")
...
Unknown Exception
抛出异常:
>>> try:
... raise ValueError("A value error happened.")#抛出异常
... except ValueError: #可以像捕获其他异常一样捕获抛出的异常
... print("ValueError in our code.")
...
ValueError in our code.
定义清理行为:
try
语句还有另一个可选的 finally
子句,目的在于定义在任何情况下都一定要执行的功能。例如:
>>> try:
... raise KeyboardInterrupt
... finally:
... print('Goodbye, world!')
...
Goodbye, world!
KeyboardInterrupt
Traceback (most recent call last):
File "<stdin>", line 2, in ?
不管有没有发生异常,finally
子句 在程序离开 try
后都一定会被执行。当 try
语句中发生了未被 except 捕获的异常(或者它发生在 except
或 else
子句中),在 finally
子句执行完后它会被重新抛出。
在真实场景的应用程序中,finally 子句用于释放外部资源(文件或网络连接之类的),无论它们的使用过程中是否出错。
以上内容均摘抄自实验楼:https://www.shiyanlou.com/courses/596/labs/2045/document