错误常常发生,可能是代码的逻辑出问题,也可能是自己不能控制的外部原因。
这里便会谈到我们该如何去保护我们的代码,避免可预见错误和不可预见场景,举个例子来说明。
>>> n = int(input("What is your age? "))
What is your age? 12
写代码时很自然的会想到是填数字,但是会出现意外情况。
>>> n = int(input("What is your age? "))
What is your age? twelve
也就是用户不填阿拉伯数字,填英文(因为这是国外)
就会出错
Trackeback (most recent call last): File ", line 1, in n = int(input("What is your age? ")) ValueError: invalid literal for int() with base 10: 'twelve'
所以我们该怎么做才能保证我们的代码在用户出现我们意想不到的行为正常工作呢?
我们先从一个模块开始
# error_handling.py def run(): a = input() b = input() if __name__ == '__main__': run()
然后加入一个函数
# error_handling.py def add(a, b): return int(a) + int(b) def run(): a = input() b = input() r = add(a,b) print(r) if __name__ == '__main__': run()
当我们输入我们理想的阿拉伯数字当然不会出错,但是如果是入twelve就会有很大问题
Traceback (most recent call last):
File "/usr/lib64/python3.10/idlelib/run.py", line 580, in runcode
exec(code, self.locals)
File "/home/mark/ics32/error_handling.py", line 12, in
run()
File "/home/mark/ics32/error_handling.py", line 8, in run
r = add(a,b)
File "/home/mark/ics32/error_handling.py", line 3, in add
return int(a) + int(b)
ValueError: invalid literal for int() with base 10: 'twelve'
这里是想将输入值换为整数。这里有几种方法,我们可以尝试将输入的值确实地转为整数,但这会使代码变得很多。最简单地办法是,解决可能地问题。试试try...except
用法:
try:
# Operation to perform
except:
# Operation to perform if an error occurs on the first operation
else:
# Operation to perform in an error does not occur on the first operation
finally:
# Operation to perform regardless of what happens to the first operation
可以变成
# error_handling.py
if __name__ == '__main__':
try:
run()
except:
print("An error has occurred")
这样当然可以运行不出错,但是当代码越来越复杂,这样会很不方便,所以我们直接在有问题的地方进行尝试。
# error_handling.py
def add(a, b):
r = 0
try:
r = int(a) + int(b)
except:
print("An error has occurred")
return r
def run():
a = input()
b = input()
r = add(a,b)
print(r)
if __name__ == '__main__':
run()
但是这样也有2点不好:(1)我们不知道是那个变量不能转换(2)用户是在run函数出问题,我们却在add函数上改进
所以可以单独加一个函数
def is_int(val):
try:
int(val)
return True
except ValueError:
return False
变成
# error_handling.py
def is_int(val):
try:
int(val)
return True
except ValueError:
return False
def add(a, b):
return int(a) + int(b)
def run():
a = input()
b = input()
if is_int(a) == False or is_int(b) == False:
print("Unable to perform operation with supplied values")
else:
r = add(a,b)
print(r)
if __name__ == '__main__':
run()



