抛出异常

#coding=utf-8

def  exceptionTest(num):

if num<0:

print "if num<0"

raise Exception("Invalid num")

else:

print num

if num == 0:

raise ZeroDivisionError("interger division or modulo by zero")

print exceptionTest(-43)

c:\Python27\Scripts>python task_test.py

if num<0

Traceback (most recent call last):

  File "task_test.py", line 14, in <module>

    print exceptionTest(-43)

  File "task_test.py", line 7, in exceptionTest

    raise Exception("Invalid num")

Exception: Invalid num

#coding=utf-8

def  exceptionTest(num):

if num<0:

print "if num<0"

raise Exception("Invalid num")

else:

print num

if num == 0:

raise ZeroDivisionError("interger division or modulo by zero")

return ""

print exceptionTest(4)

c:\Python27\Scripts>python task_test.py

4

 

#coding=utf-8

def  exceptionTest(num):

if num<0:

print "if num<0"

raise Exception("Invalid
num")

else:

print num

if num == 0:

raise ZeroDivisionError("interger
division or modulo by zero")

return ""

print
exceptionTest(0)

c:\Python27\Scripts>python task_test.py

0

Traceback (most recent call last):

  File
"task_test.py", line 14, in <module>

    print
exceptionTest(0)

  File
"task_test.py", line 11, in exceptionTest

    raise
ZeroDivisionError("interger division or modulo by zero")

ZeroDivisionError: interger division or modulo by zero

 

 

自定义异常

通过创建一个新的异常类,程序可以创建它们自己特定的异常。自定义异常都需要继承异常基类(Exception类),当然也可以继承具体的异常类(比如RuntimeError),通过直接或间接的方式。

#coding=utf-8

class
Neterror(RuntimeError):

def __init__(self,value):#重写默认的__ini__()方法

self.value=value

#触发自定义的异常

try:

raise Neterror("Bad hostname")

except
Neterror,e:

print "My exception
occurred,value:",e.value

 

c:\Python27\Scripts>python task_test.py

My exception occurred,value: Bad hostna

 

#coding=utf-8

class
ShortInputException(Exception):

''' A user-defined exception class.'''

def __init__(self,length,atleast):

Exception.__init__(self)

self.length = length

self.atleast = atleast

try:

s= raw_input('Enter something-->')

if len(s)<3:

#如果输入的内容长度小于3,触发异常

raise ShortInputException(len(s),3)

except
EOFError:

print '\nWhy did you do an EOF on me?'

except
ShortInputException,x:

print "shortInputException:The input
was of length %d,\

was
excepting at least %d"%(x.length,x.atleast)

else:

print "No exception was raised"

c:\Python27\Scripts>python task_test.py

Enter something-->234s

No exception was raised

 

c:\Python27\Scripts>python task_test.py

Enter something-->3e3

No exception was raised

 

c:\Python27\Scripts>python task_test.py

Enter something-->w

shortInputException:The input was of length 1,    was excepting at least 3

 

c:\Python27\Scripts>python task_test.py

Enter something-->

shortInputException:The input was of length 0,    was excepting at least 3

 

异常抛出机制:

1、如果在运行时发生异常,解释器会查找相应的处理语句(称为handler)。

2、要是在当前函数里没有找到的话,它会将异常传递给上层的调用函数,看看 那里能不能处理。

3、如果在最外层(全局“main”)还是没有找到的话,解释器就会退出,同时打印出traceback以便让用户找到错误产生的原因。

注意:

虽然大多数错误会导致异常,但一个异常不一定代表错误,有时候它们只是一个警告,有时候它们可能是一个终止信号,比如退出循环等

 

标准异常说明

上面列举的标准异常集,所有的异常都是内建的.。所以它们在脚本启动前或在互交命令行提示符出现时已经是可用的了。

所有的标准/内建异常都是从根异常派生的。目前,有3 个直接从BaseException 派生的异常子类:SystemExit,KeyboardInterrupt 和Exception。其他的所有的内建异常都是Exception 的子类。

Python2.5开始,所有的异常的都是BaseException
的子类。

 

 

With介绍:

with是从Python2.5引入的一个新的语法,它是一种上下文管理协议,目的在于从流程图中把 try,except 和finally 关键字和资源分配释放相关

代码统统去掉,简化try….except….finlally的处理流程。with通过__enter__方法初始化,然后在__exit__中做善后以及处理异常。所以使用with处理的对象必须有__enter__()和__exit__()这两个方法。其中__enter__()方法在语句体(with语句包裹起来的代码块)执行之前进入运行,__exit__()方法在语句体执行完毕退出后运行。

with 语句适用于对资源进行访问的场合,确保不管使用过程中是否发生异常都会执行必要的“清理”操作,释放资源,比如文件使用后自动关闭、线程中锁的自动获取和释放等。

With语句的基本语法格式如下

with expression [as target]:

with_body

参数说明:

expression:是一个需要执行的表达式;

target:是一个变量或者元组,存储的是expression表达式执行返回的结果, 可选参数。

#coding=utf-8

with open("d:\\a.txt",'r') as fp:

print fp.read()

c:\Python27\Scripts>python
task_test.py

sdfsdfsdfsdf1

with语句的工作原理:

紧跟with后面的语句会被求值,返回对象的__enter__()方法被调用,这个方法的返回值将被赋值给as关键字后面的变量,当with后面的代码块全部被执行完之后,将调用前面返回对象的__exit__()方法。

从前面我们知道,with语句最关键的地方在于被求值对象必须有__enter__()和__exit__()这两个方法,那我们就可以通过自己实现这两方法来自定义with语句处理异常。

#coding=utf-8

class opened(object):

def __init__(self,filename):

self.handle=open(filename)

print "Resource:%s" %filename

def __enter__(self):

print "[Enter%s]:Allocate
resource." %self.handle

return self.handle#可以返回不同的对象

def
__exit__(self,exc_type,exc_value,exc_trackback):

print "[Exit%s]:Free
resource." %self.handle

if exc_trackback is None:

print "[Exit%s]:Exited without
exception." %self.handle

self.handle.close()

else:

print "[Exit %s]: Exited with
exception raised." %self.handle

return False#可以省略,缺省的None也是被看作是False

with
opened("d:\\a.txt") as fp:

for line in fp.readlines():

print line

c:\Python27\Scripts>python
task_test.py

Resource:d:\a.txt

[Enter<open
file 'd:\\a.txt', mode 'r' at 0x0000000002BC7150>]:Allocate resource.

sdfsdfsdfsdf1

[Exit<open
file 'd:\\a.txt', mode 'r' at 0x0000000002BC7150>]:Free resource.

[Exit<open
file 'd:\\a.txt', mode 'r' at 0x0000000002BC7150>]:Exited without exception.

 

示例代码说明:

opened中的__enter__() 返回的是自身的引用,这个引用可以赋值给 as 子句中的fp变量;返回值的类型可以根据实际需要设置为不同的类型,不必是上下文管理器对象本身。

__exit__() 方法中对变量exc_trackback进行检测,如果不为 None,表示发生了异常,返回 False 表示需要由外部代码逻辑对异常进行处理;如果没有发生异常,缺省的返回值为 None,在布尔环境中也是被看做 False,但是由于没有异常发生,__exit__() 的三个参数都为 None,上下文管理代码可以检测这种情况,做正常处理。__exit__()方法的3个参数,分别代表异常的类型、值、以及堆栈信息。

命名空间

Random是命名空间

导入ramdom命名空间里的randint函数

#encoding=utf-8

>>>
from random import randint

>>>
print randint(10,20)

18

 

一起引入两个

>>>
from random import randint,choice

>>>
print randint(10,20)

11

>>>
print choice([1,2,3,4])

3

>>> 

 

直接用*,引入所有函数,但是坏处是如果本地有一个自定义的函数与命名空间里的函数同名,命名空间里的该函数会被覆盖

 

>>>
from random import *

>>>
print randint(10,20)

14

>>>
print choice([1,2,3,4])

4

>>> 

 

覆盖例子:

#coding=utf-8

from random import *

def randint():

return 1

print randint(1,20)

c:\Python27\Scripts>python
task_test.py

Traceback
(most recent call last):

  File "task_test.py", line 8, in
<module>

    print randint(1,20)

TypeError:
randint() takes no arguments (2 given)

 

练习:
生成一个模块a.py,里面定义一个变量c=100,定义一个函数def add(a,b) 在b.py中通过import a 和from a import *的两种方法来引入使用c变量和add函数

a.py:

import b

c=100

def add(a,b):

return a+b

 

b.py:

import a

print a.c

print a.add(1,2)

c:\Python27\Scripts>python
task_test.py

100

3

b.py:

#coding=utf-8

from a import *

print c

print add(1,2)

c:\Python27\Scripts>python
task_test.py

100

3

 

如果一个py文件中有if __name__ == '__main__':,只有在运行该文件时才会执行,该文件在别文件中引用,不会被执行

a.py:

#encoding=utf-8

c=100

def add(a,b):

return a+b

if __name__=='__main__':

print c

print add(10,20)

 

c:\Python27\Scripts>python
a.py

100

30

 

b.py:

#coding=utf-8

from a import *

print c+add(1,2)

c:\Python27\Scripts>python
task_test.py

103

没有显示a.pyif __name__==’__main__’:下边的代码

 

在b.py中import a, 则a.py中的代码会都执行一遍

import a

reload(a)

reload后会再执行一遍a中的代码

如果import a两次,则只执行一遍a中的代码

Import a

Import a

a.py:

#encoding=utf-8

c=100

def add(a,b):

return a+b

print "import a, codes in
a will run"

if __name__=='__main__':

print c

print add(10,20)

b.py:

 

#coding=utf-8

from a import *

c:\Python27\Scripts>python
task_test.py

import a,
codes in a will run

 

b.py:import 两遍

#coding=utf-8

from a import *

from a import *

c:\Python27\Scripts>python
task_test.py

import
a, codes in a will run

只执行一次

python-自定义异常,with用法的更多相关文章

  1. Python回调函数用法实例详解

    本文实例讲述了Python回调函数用法.分享给大家供大家参考.具体分析如下: 一.百度百科上对回调函数的解释: 回调函数就是一个通过函数指针调用的函数.如果你把函数的指针(地址)作为参数传递给另一个函 ...

  2. day01-day04总结- Python 数据类型及其用法

    Python 数据类型及其用法: 本文总结一下Python中用到的各种数据类型,以及如何使用可以使得我们的代码变得简洁. 基本结构 我们首先要看的是几乎任何语言都具有的数据类型,包括字符串.整型.浮点 ...

  3. oracle 集合变量以及自定义异常的用法

    oracle 集合变量以及自定义异常的用法, 在过程 record_practice 有record变量和自定义异常的用法实例.具体在3284行. CREATE OR REPLACE Package ...

  4. 【Python】关于Python有意思的用法

    开一篇文章,记录关于Python有意思的用法,不断更新 1.Python树的遍历 def sum(t): tmp=0 for k in t: if not isinstance(k,list): tm ...

  5. python中xrange用法分析

    本文实例讲述了python中xrange用法.分享给大家供大家参考.具体如下: 先来看如下示例: >>> x=xrange(0,8) >>> print x xra ...

  6. 浅谈Python在信息学竞赛中的运用及Python的基本用法

    浅谈Python在信息学竞赛中的运用及Python的基本用法 前言 众所周知,Python是一种非常实用的语言.但是由于其运算时的低效和解释型编译,在信息学竞赛中并不用于完成算法程序.但正如LRJ在& ...

  7. python scapy的用法之ARP主机扫描和ARP欺骗

    python scapy的用法之ARP主机扫描和ARP欺骗 目录: 1.scapy介绍 2.安装scapy 3.scapy常用 4.ARP主机扫描 5.ARP欺骗 一.scapy介绍 scapy是一个 ...

  8. python函数的用法

    python函数的用法 目录: 1.定义.使用函数 1.函数定义:def 2.函数调用:例:myprint() 3.函数可以当作一个值赋值给一个变量 例:a=myprint()    a() 4.写r ...

  9. python 中@ 的用法【转】

    这只是我的个人理解: 在Python的函数中偶尔会看到函数定义的上一行有@functionName的修饰,当解释器读到@的这样的修饰符之后,会先解析@后的内容,直接就把@下一行的函数或者类作为@后边的 ...

  10. Python Enum 枚举 用法汇总

    Python Enum 枚举 用法汇总 import os import sys if sys.version_info.major + sys.version_info.minor * 0.1 &l ...

随机推荐

  1. Spring Cloud Eureka 高可用注册中心

    参考:<<spring cloud 微服务实战>> 在微服务架构这样的分布式环境中,各个组件需要进行高可用部署. Eureka Server 高可用实际上就是将自己作为服务向其 ...

  2. 8.28 jQuery

    2018-8-28 18:25:27 jQuery 参考:https://www.cnblogs.com/liwenzhou/p/8178806.html 2018-8-28 19:53:19 还是讲 ...

  3. C#调用C++ DLL的方式

    动态链接库(DLL)是一个包含可由多个程序同时使用的代码和数据的库,DLL不是可执行文件.可以说在windows操作系统中随处可见,打开主分区盘下的system32.在一些项目中,如果有大量运算或者涉 ...

  4. JNUOJ 1184 - 科学计数法

    花了半个小时,强行拗出一长串又臭又长的代码,把所有情况都分了(该分的,不该分的……都分了……) #include<cstdio> #include<cstring> #incl ...

  5. Buffer和cahce的区别

    什么是Cache? 什么是Buffer? 二者的区别是什么? http://wenda.tianya.cn/wenda/thread?tid=595a1d68b3009fed Buffer和Cache ...

  6. Cache replacement policies 缓存实现算法

    Cache replacement policies - Wikipedia https://en.wikipedia.org/wiki/Cache_replacement_policies Cach ...

  7. snowflake and uuid

    分布式系统中,有一些需要使用全局唯一ID的场景,这种时候为了防止ID冲突可以使用36位的UUID,但是UUID有一些缺点,首先他相对比较长,另外UUID一般是无序的. 有些时候我们希望能使用一种简单一 ...

  8. iOS-深入理解(转载)

    RunLoop 是 iOS 和 OS X 开发中非常基础的一个概念,这篇文章将从 CFRunLoop 的源码入手,介绍 RunLoop 的概念以及底层实现原理.之后会介绍一下在 iOS 中,苹果是如何 ...

  9. 使用schemasync同步数据库表结构

    安装方式 wget http://www.schemasync.org/downloads/SchemaSync-0.9.4.tar.gz tar -xf SchemaSync-0.9.4.tar.g ...

  10. 多线程-interrupt(),isInterrupted(),interrupted()

    背景 由于使用stop方法停止线程非常暴力,可能会导致一系列问题.因此,提出一种温和的方式:请求另外一个先不要在执行了,这就是中断方式. 此外有这样的场景:编写 一个程序,需要暂停一段时间,于是调用T ...