可以通过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 捕捉异常的更多相关文章

  1. MVC 应用程序级别捕捉异常

    捕捉异常: using System; using System.IO; using System.Net; using System.Net.Http; using System.Net.Http. ...

  2. .NET [MVC] 利用特性捕捉异常

    声明:本代码只适用于.NET MVC. 先创建一个类继承ActionFilterAttribute这个抽象类以及实现IExceptionFilter接口,并实现它的方法OnException. 代码如 ...

  3. .NET WebAPI 利用特性捕捉异常

    声明:本方式及代码只使用与.NET Web API. 先创建类继承ExceptionFilterAttribute类型并复写OnException方法. 代码如下: using System; usi ...

  4. .NET Core[MVC] 利用特性捕捉异常

    声明:本方式适用于MVC.本代码只适用于.NET Core MVC. 先创建一个类继承ExceptionFilterAttribute这个抽象类,并override它的方法OnException. 代 ...

  5. ABP捕捉异常错误代码

    在服务层或者CORE层  随便哪里都可以  创建一个捕捉异常的文件夹  里面写一个LonsidException类 继承后面的接口  然后重写继承的方法  这样在ABP项目运行阶段  无论在哪里出现异 ...

  6. zzw原创_oracle循环中的异常捕捉_捕捉异常后并继续循环

    例子如下 set serveroutput on; declare   V_SQL VARCHAR2(255);   errorCode number; --异常编码     errorMsg var ...

  7. Java如何使用finally块来捕捉异常?

    在Java编程中,如何使用finally块来捕捉异常? 此示例显示如何使用finally块来通过使用e.getMessage()捕获运行时异常(Illegalargumentexception). p ...

  8. [TimLinux] Python3.6 异常继承关系

    Python3.6 异常继承结构 object └── BaseException ├── Exception │   ├── ArithmeticError │   │   ├── Floating ...

  9. python3 selenium 超时停止加载,并且捕捉异常, 进行下一步【亲测有效】

    from selenium import webdriver import os import re class GetPage: def __init__(self, url_path): self ...

随机推荐

  1. CGGeometry Reference (一)

    知识点 frame 与bounds 的区别 1.frame 是这个视图的大小在父视图的位置 . 如x 20 y 20  width 200 height 300 2.bounds 是这个视图的大小在自 ...

  2. sql问题集合

    1.sqlparameter @ 写在from前面

  3. 阿里云消息队列MQ_HTTP接入 for .NetCore 简单例子

    , , )).TotalMilliseconds;                 , , )).TotalMilliseconds;                 )                ...

  4. webstrom软件使用

    很多人都发现 http://idea.lanyus.com/ 不能激活了 很多帖子说的 http://15.idea.lanyus.com/ 之类都用不了了 选择 License server (20 ...

  5. android小游戏 飞机躲子弹

    最近android老师让每人写一个小东西,因为之前学awt时写过一个java版的飞机躲子弹,所以这次想写成android版的. 文件直接导入就行http://files.cnblogs.com/fil ...

  6. LINQ 常见用法

    以下数据源都假设为data 1.获取某列的不重复数据 List<int> ids =  data.Select(t => t.ID).Distinct().ToList(); 2.对 ...

  7. Html5 Egret游戏开发 成语大挑战(九)设置界面和声音管理

    在上一篇中,简单的使用界面元素快速实现了一个游戏中的二级页面,这种直接在游戏页面上做UI的做法并不太好,原因是,UI会让游戏的压力变大,即使它是隐蔽的,如果同样的功能在其它的地方也是一样的,那么就要写 ...

  8. MVC5 + EF6 + Bootstrap3 (15) 应用ModelState和Data Annotation做服务器端数据验证

    Slark.NET-博客园 http://www.cnblogs.com/slark/p/mvc5-ef6-bs3-get-started-server-side-validation.html 系列 ...

  9. JavaEE PO VO BO DTO POJO DAO 整理总结

    佩服能将复杂难懂的技术,抽象成简单易懂事物的人. 厌恶将简单易懂的技术,添加一堆专业术语将别人弄的头晕目眩的人. PO VO BO DTO POJO DAO 总体一览: 1.DAO[data acce ...

  10. denounce函数:Javascript中如何应对高频触发事件

    在DOM Event的世界中,以scroll.resize.mouseover等为代表的高频触发事件显得有些与众不同.通常,DOM事件只有在明确的时间点才会被触发,比如被点击,比如XMLHttpReq ...