异常与错误02-创建异常

本文详细探讨了异常处理机制,特别关注了自定义异常类的实现及其在文件操作中的应用,通过实例展示了如何更新异常参数以提供更详细的错误信息,并处理特定的权限拒绝错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

关于异常,来自《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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值