python异常处理
2021-02-20 09:19
标签:NPU class 代码块 final ISE return 字符 input sel python异常处理 标签:NPU class 代码块 final ISE return 字符 input sel 原文地址:https://www.cnblogs.com/ericness/p/12682837.htmlpython异常处理
捕获已知异常
s1 = input("请输入一个字符:")
try:
int(s1)
except IndexError as e:
print(e)
except KeyError as e:
print(e)
except ValueError as e:
print(e)
捕获未知异常
s1 = input("请输入一个字符:")
try:
int(s1)
except Exception as e:
print(e)
异常处理完整结构
try:
pass # 主代码块
except KeyError as e:
pass # 出现该异常时执行
else:
pass # 主代码块执行完,执行该块(若捕获到异常,则不执行该句)
finally:
pass # 无论异常与否,最终执行该块(不论try、except、else是否出现异常,该句都会执行)
抛出异常
s1 = input("请输入一个字符:")
try:
if len(s1) != 1:
raise Exception(KeyError) # 抛出KeyError异常
except Exception as e: # 捕获异常
print(e)
自定义异常
class MyException(Exception):
def __init__(self, code, msg):
self.error_code = code
self.error_msg = msg
def __str__(self):
return self.error_code, self.error_msg
try:
raise MyException(3000, ‘自定义异常‘)
except MyException as e:
print(e.error_code, e.error_msg)