语法错误(syntax error)
for i in range(10)
print(i)
for i in range(10)
^
SyntaxError: invalid syntax
Python的语法分析器完成,监测到错误所在文件和行号。以向上箭头标记错误位置。最后显示错误类型。
当程序监测到一个错误,解释器就无法继续执行下去,抛出异常,终止程序。
逻辑错误(logic error)
执行区间错误(runtime error)
系统根据不同的错误,抛出不同的异常。
常见异常
异常 | 描述 |
---|---|
NameError | 尝试访问一个没有申明的变量 |
ZeroDivisionError | 除数为 0 |
SyntaxError | 语法错误 |
IndexError | 索引超出序列范围 |
KeyError | 请求一个不存在的字典关键字 |
FileNotFoundError | 文件未发现错误(比如你要读的文件不存在) |
AttributeError | 尝试访问未知的对象属性 |
ModuleNotFoundError | 模块未发现 |
IndentationError | 缩进 |
1/0
Traceback (most recent call last):
File "/Users/shaojun/PycharmProjects/7.23/t1.py", line 1, in <module>
1/0
ZeroDivisionError: division by zero
b
Traceback (most recent call last):
File "/Users/shaojun/PycharmProjects/7.23/t1.py", line 1, in <module>
b
NameError: name 'b' is not defined
dic = {"name":"Tom"}
print(dic["age"])
Traceback (most recent call last):
File "/Users/shaojun/PycharmProjects/7.23/t1.py", line 2, in <module>
print(dic["age"])
KeyError: 'age'
f = open('text.txt')
Traceback (most recent call last):
File "/Users/shaojun/PycharmProjects/7.23/t1.py", line 1, in <module>
f = open('text.txt')
FileNotFoundError: [Errno 2] No such file or directory: 'text.txt'
a = 10
File "/Users/shaojun/PycharmProjects/7.23/t1.py", line 1
a = 10
^
IndentationError: unexpected indent
程序一旦发生错误,程序就无法继续运行。
为了是程序健壮,可做相关异常的处理。
try…except…
try:
try_statements
except[exception[as identifier]]:
except_statements
[else:
else_statements]
[finally:
finally_statements]
try子句
except子句
else子句
finally子句
当要离开try … except 时(无论异常是否发生),就会执行finally_statements,可以使清除错误或者收尾的语句。可给可忽略。
请输入被除数x:24
请输入除数y:a
Traceback (most recent call last):
File "/Users/shaojun/PycharmProjects/7.23/t1.py", line 2, in <module>
y = eval(input('请输入除数y:'))
File "" , line 1, in <module>
NameError: name 'a' is not defined
try:
x = eval(input('请输入被除数x:'))
y = eval(input('请输入除数y:'))
z = x / y
print('x/y=', z)
except ZeroDivisionError:
print("除数不可为0")
请输入被除数x:10
请输入除数y:0
除数不可为0
try:
x = eval(input('请输入被除数x:'))
y = eval(input('请输入除数y:'))
z = x / y
print('x/y=', z)
except ZeroDivisionError:
print("除数不可为0")
except NameError:
print("请检查变量是否赋值")
请输入被除数x:10
请输入除数y:a
请检查变量是否赋值
try:
x = eval(input('请输入被除数x:'))
y = eval(input('请输入除数y:'))
z = x / y
print('x/y=', z)
# except ZeroDivisionError:
# print("除数不可为0")
# except NameError:
# print("请检查变量是否赋值")
except Exception as e:
print(e.args)
else:
print("未捕捉到异常, x/y=", z)
finally:
print("离开try...except")
请输入被除数x:10
请输入除数y:a
("name 'a' is not defined",)
离开try...except
try:
x = eval(input('请输入被除数x:'))
y = eval(input('请输入除数y:'))
z = x / y
print('x/y=', z)
# except ZeroDivisionError:
# print("除数不可为0")
# except NameError:
# print("请检查变量是否赋值")
# except Exception as e:
# print(e.args)
except (ZeroDivisionError, NameError) as e:
print(e.args)
else:
print("未捕捉到异常, x/y=", z)
finally:
print("离开try...except")
请输入被除数x:12,
请输入除数y:2
Traceback (most recent call last):
File "/Users/shaojun/PycharmProjects/7.23/t1.py", line 4, in <module>
z = x / y
TypeError: unsupported operand type(s) for /: 'tuple' and 'int'
离开try...except
除了系统抛出的异常,我们可以用raise语句自己触发异常。
格式:
raise [Exception[,args[,traceback]]]
try:
raise NameError("Sorry,Error occurs")
except Exception as e:
print(e.args)
('Sorry,Error occurs',)
assert condition
逻辑上相当于:
if not condition:
raise AssertionError()
为断言添加一个异常参数
assert expression[,args]
Arguments
li = [1, 2]
assert len(li) >= 5, "列表元素个数小于5"
Traceback (most recent call last):
File "/Users/shaojun/PycharmProjects/7.23/t3.py", line 2, in <module>
assert len(li) >= 5, "列表元素个数小于5"
AssertionError: 列表元素个数小于5