可以通过try/except语句来实现捕获异常,如下:
bpython version 0.15 on top of Python 3.5.1+ /usr/bin/python3 >>> x=3 >>> y=0 >>> x/y Traceback (most recent call last): File "<input>", line 1, in <module> x/y ZeroDivisionError: division by zero
捕获异常:
这里只输出提示信息:
#!/usr/bin/env python # encoding: utf-8 """ @author: kamil.liu @file: except.py @time: 16-5-30 上午11:40 """ x = 3 y = 0 try: print(x/y) except ZeroDivisionError: print(‘The second number can`t be zero‘)
结果:
/usr/bin/python3.5 /home/kamil/PycharmProjects/untitled/test1/try/except.py The second number can`t be zero Process finished with exit code 0
不加参数,捕获异常:
如果捕获到异常,不处理,只传递异常,可以调用不带参数的raise,如下事例:
传递异常:
#!/usr/bin/env python # encoding: utf-8 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 = MuffledCalculator() print(calculator.calc(‘9/3‘)) #calculator.muffled = True print(calculator.calc(‘9/0‘)) """ /usr/bin/python3.5 /home/kamil/PycharmProjects/untitled/test1/try/except.py 3.0 Traceback (most recent call last): File "/home/kamil/PycharmProjects/untitled/test1/try/except.py", line 16, in <module> print(calculator.calc(‘9/0‘)) File "/home/kamil/PycharmProjects/untitled/test1/try/except.py", line 8, in calc return eval(expr) File "<string>", line 1, in <module> ZeroDivisionError: division by zero Process finished with exit code 1 """
不传递异常
#!/usr/bin/env python # encoding: utf-8 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 = MuffledCalculator() print(calculator.calc(‘9/3‘)) calculator.muffled = True print(calculator.calc(‘9/0‘)) """ /usr/bin/python3.5 /home/kamil/PycharmProjects/untitled/test1/try/except.py 3.0 Division by zero is illegal None Process finished with exit code 0 """
除0行为发生,屏蔽被打开,calc会返回None。
时间: 2024-10-12 06:54:37