您的位置:首页 > 其它

异常与错误02-创建异常

2015-11-29 00:01 141 查看
关于异常,来自《python核心编程》

#!/usr/bin/env python
# -*- coding: UTF-8 -*-

import os, socket, errno, types, tempfile

class NetworkError(IOError):
pass
class FileError(IOError):
pass

'''更新异常的参数,目标是提供更多的细节信息给用户,
这样当问题发生时能够尽快的捕捉到'''
def updArgs(args,newarg=None):
if isinstance(args,IOError):
print "111111"
myargs = []
myargs.extend([arg for arg in args])
else:
print "222222"
myargs = list(args)
if newarg:
myargs.append(newarg)
print "myargs:%s"% myargs
return tuple(myargs)

'''寻找表示permissiondenied.(没有权限.)的错误 EACCES.
其他所有的 IOError 异常我们将不加修改的传递 '''
def fileArgs(file,mode,args):
if args[0] == errno.EACCES and 'access' in dir(os):
print "fun:%s"% errno.EACCES
print "fun:%s"% dir(os)
perms = ''
permd = {'r':os.R_OK,'w':os.W_OK,'x':os.X_OK}
print "fun:%s"% type(permd)
pkeys = permd.keys()
print "fun:%s"% type(pkeys)
pkeys.sort()
pkeys.reverse()

for eachPerm in 'rwx':
if os.access(file,permd[eachPerm]):
perms += eachPerm
else:
perms += '-'

if isinstance(args,IOError):
myargs = []
myargs.extend([arg for arg in args])
else:
myargs = list(args)
myargs[1] = "'%s' %s (perms:'%s')" % (mode,myargs[1],perms)
myargs.append(args.filename)
print "%s"% args.filename
print "myargs:%s"% myargs
else:
print "22222222"
myargs = args
return tuple(myargs)

def myconnect(sock,host,port):
try:
sock.connect((host,port))
except socket.error,args:
print "args[0]:%s"% args[0]
print "args[1]:%s"% args[1]
myargs = updArgs(args)
print "%d"% len(myargs)
if len(myargs) == 1:
myargs = (errno.ENXIO,myargs[0])
raise NetworkError,updArgs(myargs,host + ':' + str(port))

def myopen(file,mode='r'):
try:
fo = open(file,mode)
except IOError,args:
print "%s"% args[0]
print "%s"% args[1]
raise FileError,fileArgs(file,mode,args)
return fo

def testfile():
file = tempfile.mktemp()
print "xxxxx:%s"% (file)
f = open(file, 'w')
f.close()

for eachTest in ((0,'r'),(0100,'r'),(0400,'w'),(0500,'w')):
try:
os.chmod(file,eachTest[0])
f = myopen(file,eachTest[1])
except FileError,args:
print "%s"% (args.__class__.__name__)
print "%s:::%s"% (args.__class__.__name__,args)
else:
print file,"opened ok... perm ignored"
f.close()
os.chmod(file,0777)
os.unlink(file)

def testnet():
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
for eachHost in ('deli',8080):
try:
myconnect(s,'deli',8080)
except NetworkError,args:
print "%s: %s"% (args.__class__.__name__,args)
if __name__ == '__main__':
testfile()
testnet()


输出:

D:\Python27\test>try-except02.py
xxxxx:c:\users\yhb\appdata\local\temp\tmprtcdyp
13
Permission denied
fun:13
fun:['F_OK', 'O_APPEND', 'O_BINARY', 'O_CREAT', 'O_EXCL', 'O_NOINHERIT', 'O_RANDOM', 'O_RDONLY', 'O_RDWR', 'O_SEQUENTIAL', 'O_SHORT_LIVED', 'O_TEMPORARY', 'O_TEXT', 'O_TRUNC', 'O_WRONLY', 'P_DETACH', 'P_NOWAIT', 'P_NOWAITO', 'P_OVERLAY', 'P_WAIT', 'R_OK', 'SEEK_CUR', 'SEEK_END', 'SEEK_SET', 'TMP_MAX', 'UserDict', 'W_OK', 'X_OK', '_Environ', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '_copy_reg', '_execvpe', '_exists', '_exit', '_get_exports_list', '_make_stat_result', '_make_statvfs_result', '_pickle_stat_result', '_pickle_statvfs_result', 'abort', 'access', 'altsep', 'chdir', 'chmod', 'close', 'closerange', 'curdir', 'defpath', 'devnull', 'dup', 'dup2', 'environ', 'errno', 'error', 'execl', 'execle', 'execlp', 'execlpe', 'execv', 'execve', 'execvp', 'execvpe', 'extsep', 'fdopen', 'fstat', 'fsync', 'getcwd', 'getcwdu', 'getenv', 'getpid', 'isatty', 'kill', 'linesep', 'listdir', 'lseek', 'lstat', 'makedirs', 'mkdir', 'name', 'open', 'pardir', 'path', 'pathsep', 'pipe', 'popen', 'popen2', 'popen3', 'popen4', 'putenv', 'read', 'remove', 'removedirs', 'rename', 'renames', 'rmdir', 'sep', 'spawnl', 'spawnle', 'spawnv', 'spawnve', 'startfile', 'stat', 'stat_float_times', 'stat_result', 'statvfs_result', 'strerror', 'sys', 'system', 'tempnam', 'times', 'tmpfile', 'tmpnam', 'umask', 'unlink', 'unsetenv', 'urandom', 'utime', 'waitpid', 'walk', 'write']
fun:<type 'dict'>
fun:<type 'list'>
c:\users\yhb\appdata\local\temp\tmprtcdyp
myargs:[13, "'w' Permission denied (perms:'r-x')", 'c:\\users\\yhb\\appdata\\local\\temp\\tmprtcdyp']
FileError
FileError:::[Errno 13] 'w' Permission denied (perms:'r-x'): 'c:\\users\\yhb\\appdata\\local\\temp\\tmprtcdyp'
13
Permission denied
fun:13
fun:['F_OK', 'O_APPEND', 'O_BINARY', 'O_CREAT', 'O_EXCL', 'O_NOINHERIT', 'O_RANDOM', 'O_RDONLY', 'O_RDWR', 'O_SEQUENTIAL', 'O_SHORT_LIVED', 'O_TEMPORARY', 'O_TEXT', 'O_TRUNC', 'O_WRONLY', 'P_DETACH', 'P_NOWAIT', 'P_NOWAITO', 'P_OVERLAY', 'P_WAIT', 'R_OK', 'SEEK_CUR', 'SEEK_END', 'SEEK_SET', 'TMP_MAX', 'UserDict', 'W_OK', 'X_OK', '_Environ', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '_copy_reg', '_execvpe', '_exists', '_exit', '_get_exports_list', '_make_stat_result', '_make_statvfs_result', '_pickle_stat_result', '_pickle_statvfs_result', 'abort', 'access', 'altsep', 'chdir', 'chmod', 'close', 'closerange', 'curdir', 'defpath', 'devnull', 'dup', 'dup2', 'environ', 'errno', 'error', 'execl', 'execle', 'execlp', 'execlpe', 'execv', 'execve', 'execvp', 'execvpe', 'extsep', 'fdopen', 'fstat', 'fsync', 'getcwd', 'getcwdu', 'getenv', 'getpid', 'isatty', 'kill', 'linesep', 'listdir', 'lseek', 'lstat', 'makedirs', 'mkdir', 'name', 'open', 'pardir', 'path', 'pathsep', 'pipe', 'popen', 'popen2', 'popen3', 'popen4', 'putenv', 'read', 'remove', 'removedirs', 'rename', 'renames', 'rmdir', 'sep', 'spawnl', 'spawnle', 'spawnv', 'spawnve', 'startfile', 'stat', 'stat_float_times', 'stat_result', 'statvfs_result', 'strerror', 'sys', 'system', 'tempnam', 'times', 'tmpfile', 'tmpnam', 'umask', 'unlink', 'unsetenv', 'urandom', 'utime', 'waitpid', 'walk', 'write']
fun:<type 'dict'>
fun:<type 'list'>
c:\users\yhb\appdata\local\temp\tmprtcdyp
myargs:[13, "'w' Permission denied (perms:'r-x')", 'c:\\users\\yhb\\appdata\\local\\temp\\tmprtcdyp']
FileError
FileError:::[Errno 13] 'w' Permission denied (perms:'r-x'): 'c:\\users\\yhb\\appdata\\local\\temp\\tmprtcdyp'
c:\users\yhb\appdata\local\temp\tmprtcdyp opened ok... perm ignored
args[0]:11001
args[1]:getaddrinfo failed
111111
myargs:[11001, 'getaddrinfo failed']
2
222222
myargs:[11001, 'getaddrinfo failed', 'deli:8080']
NetworkError: [Errno 11001] getaddrinfo failed: 'deli:8080'
args[0]:11001
args[1]:getaddrinfo failed
111111
myargs:[11001, 'getaddrinfo failed']
2
222222
myargs:[11001, 'getaddrinfo failed', 'deli:8080']
NetworkError: [Errno 11001] getaddrinfo failed: 'deli:8080'

D:\Python27\test>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: