了解Python中内置的异常类型
错误和异常:
错误:语法错误&逻辑错误
异常:在语法上是正确的,但尝试执行时,仍然可能会引发错误
-异常不一定会导致严重的后果
-如果不捕获和处理异常,程序不会对其进行处理,此时会显示异常信息
常见的内置异常:
NmaeError:尝试访问一个没有声明的变量
ZeroDivisionError:除数(分母)为0
IndexError:索引超出序列范围
KeyError:请求一个不存在的字典的键
IOError:输入/输出错误
AttributeError:尝试方位一个未知的对象属性
异常处理:
while True:
try:
x = int(input('input an int:'))
r = 10 / x
print(r)
except:
print('you shoud not put zero.')
break
多个异常
while True:
try:
x = int(input('input an int:'))
r = 10 / x
print(r)
except ZeroDivisionError:
print('you shoud not put zero.')
break
except SyntaxError:
print('input a number.')
两个异常合并
while True:
try:
x = int(input('input an int:'))
r = 10 / x
print(r)
except (ZeroDivisionError,SyntaxError) as e:
print(e)
break
没有异常执行else
>>> try:
... print('hello')
... except ValueError:
... print('exception')
... else:
... print('try,else')
...
hello
try,else
>>> try:
... 1/0
... except ZeroDivisionError as e:
... print(e)
...
division by zero
增加finally,执行expect中break之前先执行了finally
while True:
try:
x = int(input('input an int:'))
r = 10 / x
print(r)
except ZeroDivisionError as e:
print(e)
break
finally:
print('goodbye')
break
抛出异常:raise,允许强制发生指定的异常
>>> try:
... raise NameError('python')
... except NameError:
... print('exception')
... raise
...
exception
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
NameError: python
注意上面的rasie强制抛出
断言
assert语句,发起条件判断
>>> x = -2
>>> assert x<0
>>> assert x >0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError
掌握捕获异常的语句
while True:
try:
age = int(input('How old are you?'))
assert age > 0
if age > 150:
raise ValueError('Are you a god?')
elif (age <=150) and (age > 80):
print('Wish you good health.')
elif (age < 60) and (age > 30):
print('Work hard')
else:
print('I envy you.')
except (ValueError,AssertionError):
print('find your glasses.')
break