class MuffledCalculator: muffled = False def calc(self, expr): try: return eval(expr) except ZeroDivisionError: if self.muffled: print('Division by zero is illegal') else: raise
calculator.calc('10/0') Traceback (most recent call last): File "<pyshell#90>", line 1, in <module> calculator.calc('10/0') File "<pyshell#87>", line 5, in calc return eval(expr) File "<string>", line 1, in <module> ZeroDivisionError: division by zero
calculator.muffled = True calculator.calc('10/0') Division by zero is illegal
try: x = int(input('Enter the first number: ')) y = int(input('Enter the second number: ')) value = x / y print('x / y is ', value) except ZeroDivisionError: print("The second number can't be zero!") except TypeError: print("That wasn't a number, was it?")
如果要使用一个 except 子句捕获多种异常,可以使用元组来指定异常类型:
1 2 3 4 5 6 7
try: x = int(input('Enter the first number: ')) y = int(input('Enter the second number: ')) value = x / y print('x / y is ', value) except (ZeroDivisionError, TypeError): print('Input a wrong number!')
try: x = int(input('Enter the first number: ')) y = int(input('Enter the second number: ')) value = x / y print('x / y is ', value) except (ZeroDivisionError, TypeError) as e: print(e)
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 Exception as e: print('Invalid input,', e) print('pls try again.') else: break
当没有引发异常时将执行 else 语句中的 break 进而跳出循环。
finally 子句
finally 子句可用于在发生异常时执行清理工作,是 try 子句配套的命令。
1 2 3 4 5 6
x = None try: 1 / 0 finally: print('Cleaning up ...') del x
ignore_exception() Traceback (most recent call last): File "/usr/lib64/python3.12/idlelib/run.py", line 580, in runcode exec(code, self.locals) File "<pyshell#28>", line 1, in <module> File "<pyshell#20>", line 2, in ignore_exception File "<pyshell#14>", line 2, in faulty Exception: Something is wrong
from warnings import filterwarnings filterwarnings("ignore") warn('warning') filterwarnings("error") warn('warning') Traceback (most recent call last): File "<pyshell#44>", line 1, in <module> warn('warning') UserWarning: warning
还可以根据异常来过滤掉特定类型的警告:
1 2 3 4 5 6 7 8 9
filterwarnings("ignore",category=DeprecationWarning) warn('This func is too old.', DeprecationWarning)
filterwarnings("error",category=DeprecationWarning) warn('This func is too old.', DeprecationWarning) Traceback (most recent call last): File "<pyshell#54>", line 1, in <module> warn('This func is too old.', DeprecationWarning) DeprecationWarning: This func is too old.
评论· · · · · ·