尝试:除了:不工作

10 python exception-handling exception

所以我遇到了一个问题:try:except:机制似乎在python中没有正常工作.

这是我的两个文件的内容.

pytest1.py

import pytest2

class MyError( Exception ):
    def __init__( self, value ):
        self.value = value

    def __str__( self ):
        return repr( self.value )

def func1():
    raise MyError( 'This is an error' )

def func3():
    pytest2.func2()

if __name__ == '__main__':
    try:
        func3()
    except MyError, e:
        print 'I should catch here.'
    except:
        print 'Why caught here?'
Run Code Online (Sandbox Code Playgroud)

pytest2.py

from pytest1 import func1

def func2():
    func1()
Run Code Online (Sandbox Code Playgroud)

执行第一个文件会产生以下输出:

$ python pytest1.py
Why caught here?
Run Code Online (Sandbox Code Playgroud)

基本上,例外没有被抓住.如果我打印出异常类型,它将打印<pytest1.MyError>而不是仅打印<MyError>.我想这是一些奇怪的周期性参考事物,但它似乎仍然应该工作.

Win*_*ert 9

主python程序始终作为模块导入__main__.

导入时pytest2,它不会重用现有模块,因为最初导入的模块的名称__main__不是pytest2.结果是pytest1多次运行生成多个异常类.__main__.MyErrorpytest1.MyError你最终抛出一个试图赶上其他.

因此,不要尝试从其他模块导入主模块.