Python3 捕捉异常
Posted 侠之大者
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python3 捕捉异常相关的知识,希望对你有一定的参考价值。
可以通过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。
以上是关于Python3 捕捉异常的主要内容,如果未能解决你的问题,请参考以下文章
Kotlin 协程协程异常处理 ③ ( 协程异常处理器 CoroutineExceptionHandler 捕获异常 | 验证 CoroutineScope 协程的异常捕捉示例 )
Kotlin 协程协程异常处理 ③ ( 协程异常处理器 CoroutineExceptionHandler 捕获异常 | 验证 CoroutineScope 协程的异常捕捉示例 )