python跟Java一样,也有类似try...catch...的异常处理机制。 在程序中有做异常处理最大的好处是代码段出现异常之后,仍然能够继续执行下去。
一、捕获一种具体的异常的写法:
d = {}
try:
print(d('apple'))
except KeyError as err:
print('Error: {}'.format(err))
print('...')
二、如果有多种Error的话,可以这么写:
#写法一:
try:
num = input("please input the dividend:")
num = int(num)
num = 100 / num
except (ValueError, ZeroDivisionError) as err:
print('Error:{}'.format(err))
print('...')
#写法二:
try:
num = input("please input the dividend:")
num = int(num)
num = 100 / num
except ValueError as err:
print('Value Error:{}'.format())
except ZeroDivisionError as err:
print('ZeroDivision Error:{}'.format())
print('...')
#写法三,更安全的写法,在你无法保证程序覆盖所有的异常类型的情况下:
try:
num = input("please input the dividend:")
num = int(num)
num = 100 / num
except ValueError as err:
print('Value Error:{}'.format())
except ZeroDivisionError as err:
print('ZeroDivision Error:{}'.format())
except Exception as err:
print('Other error:{}'.format(err))
#写法四,匹配任意类型的异常(包括系统异常)
try:
num = input("please input the dividend:")
num = int(num)
num = 100 / num
except ValueError as err:
print('Value Error:{}'.format())
except ZeroDivisionError as err:
print('ZeroDivision Error:{}'.format())
except:
print('Other error')
print('...')
#写法五,try...except...finally
try:
pass
except:
pass
finally:
pass
三、自定义异常:
class MyError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return ("Detail_message:{}".format(repr(self.value)))
try:
raise MyError('message')
except MyError as err:
print('error:{}'.format(err))
四、使用场景:
#对json格式的数据进行解码:
try:
data = json.loads(raw_data)
....
except JSONDecodeError as err:
print('JSONDecodeError: {}'.format(err))