+ -
当前位置:首页 → 问答吧 → 紧急求救~临睡最后一问

紧急求救~临睡最后一问

时间:2011-08-31

来源:互联网

大家好,请教个问题,同样的一段程序,放在两个不同的.PY文件里执行情况不一样。
Python code
#MetaError.py
#encoding=utf-8
import sys

class MetaError(Exception):
    def __init__(self,msg,type):
        self.msg = msg
        self.type = type

class MetaManagerError(MetaError):
    def __init__(self,msg,type):
        self.msg = msg
        self.type = type
    
def test():
    try:
        print 'xx'
        print yy
    except:
        exInfo = sys.exc_info()
        raise MetaManagerError,(exInfo[1],exInfo[2].tb_lineno)

try:
    test()
except Exception,e:
    print type(e)
#运行结果如下
joe@joe:/mnt $ python MetaError.py 
xx
<class '__main__.MetaManagerError'>



而如果我把后面那个test函数放到另外一个.PY文件里执行,打印出来的异常类型就不一样了

Python code
import MetaError

def test():
    try:
        print 'xx'
        print yy
    except:
        exInfo = sys.exc_info()
        raise MetaError.MetaManagerError,(exInfo[1],exInfo[2].tb_lineno)

try:
    test()
except Exception,e:
    print type(e)
#运行结果如下
joe@joe:/mnt $ python a.py
xx
<class 'MetaError.MetaManagerError'>
xx
<type 'exceptions.NameError'>
Traceback (most recent call last):
  File "a.py", line 15, in <module>
    print e.msg
AttributeError: 'exceptions.NameError' object has no attribute 'msg'


放在同一个文件里,类型就是我自定义的异常<class 'MetaError.MetaManagerError'>;分开两个不同的.PY文件,异常类型就变为<type 'exceptions.NameError'>了
为什么呢?

作者: wh62592855   发布时间: 2011-08-31

找到问题所在了,在后面那个.PY文件里没有import sys,因此在调用exInfo = sys.exc_info()时出错

作者: wh62592855   发布时间: 2011-08-31

如果你自己写的代码抛异常了,你能自己阅读异常栈然后检查代码找出原因吗?
请使用同样的技术解决这个问题。
自己写的代码都找不出来原因,通常都是自己不够仔细,或者不够自信,或者人为给自己制造麻烦(比如所有的输出都一样,分辨不清是哪行输出对应哪行代码,比如乱catch异常)造成的。

另外请下次保证你贴出来的代码和出错信息是匹配的。贴错误的信息太浪费时间(浪费自己的时间也就罢了,浪费别人的时间是不可饶恕的)。
根本没看到你的a.py里15行有什么print e.msg。而且你的代码里把错误都捕获了,哪来的异常栈?

作者: iambic   发布时间: 2011-09-01