python 中报错分为两类:语法错误 和 异常。
- 语法错误 会有 SyntaxError 的提示
- 异常 会有具体 异常类型 的提示(i.e. ValueError, AssertionError, IndexError, KeyError, TypeError)
while True:
try:
x = int(input('Enter a number: '))
break
except:
print('Not a valid number!')
finally:
print('\nEnd!\n')
try: try 语句
中的唯一必需子句
except:运行 try 时遇到异常,则 跳到 except 块中
else:没有遇到异常,则跳到 else 块中
finally:在离开try 语句之前,总会执行的代码块
也可以指定在 except
块中处理哪类错误:
try:
# some code
except ValueError:
# some code
except KeyboardInterrupt:
# some code
如果希望一个代码块处理多种异常,可以在 except
后面添加异常元组:
try:
# some code
except (ValueError, KeyboardInterrupt):
# some code
可以如下所示,访问错误消息:
try:
# some code
except Exception as e:
# some code
print("Exception occurred: {}".format(e))
练习题:
def create_groups(items, num_groups):
try:
size = len(items) // num_groups
except ZeroDivisionError:
print("WARNING: Returning empty list. Please use a nonzero number.")
return []
else:
groups = []
for i in range(0, len(items), size):
groups.append(items[i:i + size])
return groups
finally:
print("{} groups returned.".format(num_groups))
print("Creating 6 groups...")
for group in create_groups(range(32), 6):
print(list(group))
print("\nCreating 0 groups...")
for group in create_groups(range(32), 0):
print(list(group))