python学习Day12-异常
异常,逻辑错误
import math
for i in range(10):
input_number = input('write a number:')
if input_number == 'q':
break
result = math.log(float(input_number))
print(result)
write a number:1
0.0
write a number:2
0.6931471805599453
write a number:3
1.0986122886681098
write a number:-3
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-1-29af1469e47d> in <module>
4 if input_number == 'q':
5 break
----> 6 result = math.log(float(input_number))
7 print(result)
ValueError: math domain error
异常捕获
import math
for i in range(10):
try:
input_number = input('write a number:')
if input_number == 'q':
break
result = math.log(float(input_number))
print(result)
except Exception:
print('ValueError:input must > 0')
write a number:1
0.0
write a number:2
0.6931471805599453
write a number:-1
ValueError:input must > 0
write a number:q
捕捉异常(越精确越好)
import math
for i in range(10):
try:
input_number = input('write a number:')
if input_number == 'q':
break
result = math.log(float(input_number))
print(result)
except Exception:
print('ValueError:input must > 0')
except ZeroDivisionError:
print('ZeroDivisionError:input must != 0')
write a number:-1
ValueError:input must > 0
write a number:0
ValueError:input must > 0
write a number:q
异常继承与重写
class TangError(ValueError):
pass
cur_list = ['java','python','php']
while True:
cur_input = input()
if cur_input not in cur_list:
raise TangError('Invaild input:%s'%cur_input)
java
jia
---------------------------------------------------------------------------
TangError Traceback (most recent call last)
<ipython-input-7-831ae4943df0> in <module>
5 cur_input = input()
6 if cur_input not in cur_list:
----> 7 raise TangError('Invaild input:%s'%cur_input)
TangError: Invaild input:jia
finally关键字总会在执行
try:
print('hello')
finally:
print('finally')
hello
finally
try:
1/0
finally:
print('finally')
finally
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
<ipython-input-9-ec46fcef4e68> in <module>
1 try:
----> 2 1/0
3 finally:
4 print('finally')
ZeroDivisionError: division by zero
完整的异常处理
try:
1/0
except:
print('except')
finally:
print('finally')
except
finally
未完待续