Bob*_*lan 7 python exception-handling python-2.7
我有一个奇怪的问题.为了有一个简短的最小工作示例(MWE),让我们假设Connect()返回一个urllib3.connection.HTTPConnection对象.我们还假设我还有其他一些异常,如果'magicword'在错误消息中找到我想忽略的话(不是实际的单词,但是,嘿,这是一个MWE).
MWE:
try:
conn_obj = Connect()
except Exception as e: # there are some other exceptions I want to ignore
if 'magicword' not in e.message:
print 'fatal error: {}'.format(e.message)
Run Code Online (Sandbox Code Playgroud)
这在我的机器上正常工作并在遇到时打印"致命错误"并忽略其他异常(在这种情况下应该如此).
但是,在同事的计算机上,不会处理错误,而是会崩溃并创建回溯.这是我的机器上完全相同的错误,只有他不会打印和崩溃而不是处理.我们都使用完全相同的操作系统(Windows 7).
显然不处理特定的异常并不理想,所以我尝试了这条路线:
from urllib3.exceptions import NewConnectionError
try:
conn_obj = Connect()
except NewConnectionError as nce:
print 'fatal error: {}'.format(e.message)
except Exception as e: # there are some other exceptions I want to ignore
if 'magicword' not in e.message:
print 'fatal error: {}'.format(e.message)
Run Code Online (Sandbox Code Playgroud)
那也行不通.出于某种原因,它不会在他的盒子上捕获例外.为什么可以在我的机器上处理异常但不在他的机器上处理?
更新:
连接对象在pyelasticsearch第三方库中引发.我总是能够很好地捕获它,但它并没有被别人的机器上使用相同的代码捕获.这是我写的一个文件,用于测试在显式引发时是否捕获到错误:
from urllib3.exceptions import NewConnectionError
def error_test(test_num):
print '\n\n'
try:
if test_num == 1:
print 'TEST 1: See if NewConnectionError is caught specifically'
raise NewConnectionError('no pool', 'test one')
elif test_num == 2:
print 'TEST 2: See if RuntimeError is caught related to magicword'
raise RuntimeError('test two magicword catching test')
elif test_num == 3:
print 'TEST 3: See if RuntimeError is caught NOT related to magicword'
raise RuntimeError('test three')
except NewConnectionError as nce:
print 'Test 1 passed successfully.\n\n{}'.format(nce.message)
except Exception as e:
if 'magicword' not in e.message:
print 'Test 3 passed successfully.\n\n{}'.format(e.message)
else:
print 'Test 2 passed successfully.\n\n{}'.format(e.message)
error_test(1)
error_test(2)
error_test(3)
Run Code Online (Sandbox Code Playgroud)
这个测试在我们的两台机器上完美运行.因此,通过让第三方库涉及的某些东西在我们的机器之间是不一致的(这实际上是在pyinstaller编译的二进制文件中,因此库差异不应该发挥作用).
| 归档时间: |
|
| 查看次数: |
6683 次 |
| 最近记录: |