python3 有两种错误:语法错误和异常
1.语法错误
粗心导致,应尽量避免
2. 异常
运行期间检测到的错误被称为异常
3. 异常处理
- try语句
while True:
try:
x = int(input("Please enter a number: "))
break
except ValueError:
print("Oops! That was no valid number. Try again ")
for arg in sys.argv[1:]:
try:
f = open(arg, 'r')
except IOError:
print('cannot open', arg)
else: #若try执行过程中无异常,执行else语句中的内容
print(arg, 'has', len(f.readlines()), 'lines')
f.close()
- 抛出异常:raise
- 自定义异常
- 定义清理行为:finally
def divide(x, y):
try:
result = x / y
except ZeroDivisionError:
print("division by zero!")
else:
print("result is", result)
finally:
print("executing finally clause")
- 预定义清理行为:with
with open("myfile.txt") as f:
for line in f:
print(line, end="")