设置特定异常提示语:
#单独作用 try: x=int(input('enter the first:')) y=int(input('enter the second:')) print(x/y) except ZeroDivisionError: print("the second number can't be zero") enter the first:12 enter the second:0 the second number can't be zero
#写进类型 class muffledcal: muffled=False def cal(self,expr): try: return eval(expr) except ZeroDivisionError: if self.muffled: print('division by zero') else: raise calculator=muffledcal() calculator.cal('10/2') 5.0 calculator.cal('10/0') Traceback (most recent call last): File "<pyshell#42>", line 1, in <module> calculator.cal('10/0') File "<pyshell#30>", line 5, in cal return eval(expr) calculator.muffled=True calculator.cal('10/0') division by zero File "<string>", line 1, in <module> ZeroDivisionError: division by zero
所有错误均显示同样:
try: x = int(input('Enter the first number: ')) y = int(input('Enter the second number: ')) print(x / y) except: print('Something wrong happened ...')
没引发错误时跳出循环:
while True: try: x = int(input('Enter the first number: ')) y = int(input('Enter the second number: ')) value = x / y print('x / y is', value) except: print('Invalid input. Please try again.') else: break
无论有无错误都结束:
x = None try: x = 1 / 0 finally: print('Cleaning up ...') del x
检查有无赋值的高效做法:
#低效 def describe_person(person): print('Description of', person['name']) print('Age:', person['age']) if 'occupation' in person: print('Occupation:', person['occupation']) #高效 def describe_person(person): print('Description of', person['name']) print('Age:', person['age']) try: print('Occupation:', person['occupation']) except KeyError: pass
过滤警告:
from warnings import filterwarnings filterwarnings("ignore") #过滤ignore类型的警告 from warnings import warn warn("anyone out there?")
raise使用:
#处理错误并报出错误类型 eval=None try: print(eval=10/0) except ZeroDivisionError: print('10/2') raise 10/2 Traceback (most recent call last): File "<pyshell#67>", line 2, in <module> print(eval=10/0) ZeroDivisionError: division by zero
#自定义特定类型错误,raise该类型错误 class detailed(Exception): #detailed为一种类型的错误 def __init__(self,message,code,severity): super().__init__(message) #super获取超类 self.code=code self.severity=severity def some_function(condition): if condition: raise detailed("Detailed error description: The specified condition has been met.", 400, "error") #触发错误 return "Function executed successfully without raising an error." try: result=some_function(True) #触发错误,执行except except detailed as e: print(f"caught a detailederror:{e}") print(f"error code:{e.code}") print(f"severity:{e.severity}") else: print(result) caught a detailederror:Detailed error description: The specified condition has been met. error code:400 severity:error