错误与异常
# 异常
>>> 10 * (1/0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
10 * (1/0)
~^~
ZeroDivisionError: division by zero
>>> 4 + spam*3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
4 + spam*3
^^^^
NameError: name 'spam' is not defined
>>> '2' + 2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
'2' + 2
~~~~^~~
TypeError: can only concatenate str (not "int") to str
# 异常处理(try)
while True:
try:
x = int(input("Please enter a number: "))
break
except ValueError:
print("Oops! That was no valid number. Try again...")
异常实例对象:
except Exception as e:
print(f'caught {type(e)}: e')
类似于 Java 的 catch(Exception e)
# 异常抛出(raise)
>>> raise NameError('HiThere')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
raise NameError('HiThere')
NameError: HiThere
- 类似于 Java 的
throw new NameError("HiThere")
raise
(opens new window) 唯一的参数就是要触发的异常。这个参数必须是异常实例或异常类(派生自BaseException
(opens new window) 类,例如Exception
(opens new window) 或其子类)
raise ValueError # 'raise ValueError()' 的简化
如果只想判断是否触发了异常,但并不打算处理该异常,则可以使用更简单的 raise
(opens new window) 语句重新触发异常:
>>> 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 <module>
raise NameError('HiThere')
NameError: HiThere
# 异常自定义
直接或间接继承 Exception
类的类,即为异常类,约定异常类命名以 Error
结尾。具体如何定义类参考下章。
# finally
与其他语言的 try 语句类似,python 的 try 也有 finally 可选子句,作用也相似:任何情况下都会执行
>>> try:
... raise KeyboardInterrupt
... finally:
... print('Goodbye, world!')
复杂示例
def divide(x, y):
try:
result = x / y
except ZeroDivisionError:
print("division by zero!")
else: # try代码块正常执行(无异常)时触发
print("result is", result)
finally:
print("executing finally clause")
divide(2, 1)
divide(2, 0)
divide("2", "1")
# with
自动处理释放资源逻辑
with open("myfile.txt") as f:
for line in f:
print(line, end="")
上次更新: 2024/10/11, 23:55:46