错误 vs 异常

语法错误,无法被识别与执行

1
2
3
name = 'x'
if name is not None # SyntaxError: invalid syntax
print(name)

异常 - 语法正确,可以被执行,但在执行过程中遇到错误,抛出异常,并终止程序

1
2
3
# 10 / 0  # ZeroDivisionError: division by zero
# order * 2 # NameError: name 'order' is not defined
# 1 + [1, 2] # TypeError: unsupported operand type(s) for +: 'int' and 'list'

处理异常

try-except
except block 只接受与它相匹配的异常类型并执行

1
2
3
4
5
6
try:
s = input('please enter two numbers separated by comma: ')
num1 = int(s.split(',')[0].strip())
num2 = int(s.split(',')[1].strip())
except ValueError as err:
print('Value Error: {}'.format(err))

在 except block 中加入多种异常的类型

1
2
3
4
5
6
try:
s = input('please enter two numbers separated by comma: ')
num1 = int(s.split(',')[0].strip())
num2 = int(s.split(',')[1].strip())
except (ValueError, IndexError) as err:
print('Error: {}'.format(err))
1
2
3
4
5
6
7
8
try:
s = input('please enter two numbers separated by comma: ')
num1 = int(s.split(',')[0].strip())
num2 = int(s.split(',')[1].strip())
except ValueError as err:
print('Value Error: {}'.format(err))
except IndexError as err:
print('Index Error: {}'.format(err))

很难覆盖所有的异常类型,在最后的一个 except block,声明其处理的异常类型为 Exception
Exception - 是其它所有非系统异常基类

1
2
3
4
5
6
7
8
9
10
try:
s = input('please enter two numbers separated by comma: ')
num1 = int(s.split(',')[0].strip())
num2 = int(s.split(',')[1].strip())
except ValueError as err:
print('Value Error: {}'.format(err))
except IndexError as err:
print('Index Error: {}'.format(err))
except Exception as err:
print('Other Error: {}'.format(err))

在 except 后省略异常类型,表示与任意异常(包括系统异常非系统异常等)匹配 - 不推荐(过于宽泛

1
2
3
4
5
6
7
8
9
10
try:
s = input('please enter two numbers separated by comma: ')
num1 = int(s.split(',')[0].strip())
num2 = int(s.split(',')[1].strip())
except ValueError as err:
print('Value Error: {}'.format(err))
except IndexError as err:
print('Index Error: {}'.format(err))
except: # too broad exception
print('Other Error')

多个 except 声明的异常类型与实际相匹配,只有最前面的 except block 会被执行

finally - 无论发生什么情况,finally block 中的语句都会被执行,即便在 try 和 except 中使用了 return 语句

1
2
3
4
5
6
7
8
9
10
11
12
import sys

f = None
try:
f = open('params.json', 'r')
print(f.read())
except OSError as err:
print(f"Error: {err}")
except:
print("Unexpected error: ", sys.exc_info()[0])
finally: # always executed
f.close()

with open 会在最后自动关闭文件,更加简洁

自定义异常

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class MyInputError(Exception):
"""
Exception raised when there are errors in input
"""

def __init__(self, value): # Constructor
self.value = value

def __str__(self): # __str__ is to print() the value
return "{} is invalid input".format(repr(self.value))


try:
raise MyInputError(1)
except MyInputError as err:
print('error: {}'.format(err)) # error: 1 is invalid input