简体   繁体   English

在Python中尝试除了块 - 如何理解异常在哪里?

[英]Large try except block in Python - how to understand where was an exception?

I have a program (not mine) that has a large try - except block. 我有一个程序(不是我的)有一个很大的尝试 - 除了块。 Somewhere in this block there is an exception. 在这个区块的某个地方有一个例外。 what is the best way to find out the exact string of code where it happens? 找出它发生的确切代码串的最佳方法是什么?

You can use print_exc in the except block 您可以在except块中使用print_exc

import traceback
traceback.print_exc()

Example: 例:

import traceback
try:
    pass
    pass
    pass
    pass
    pass
    raise NameError("I dont like your name")
    pass
    pass
    pass
    pass
    pass
except Exception, e:
    traceback.print_exc()

Output 产量

Traceback (most recent call last):
  File "/home/thefourtheye/Desktop/Test.py", line 8, in <module>
    raise NameError("I dont like your name")
NameError: I dont like your name

Ah, if you don't want an exception to be raised, you can just have the error message, then pass: 啊,如果你不想引发异常,你可以得到错误信息,然后传递:

>>> try:
    raise ValueError("A stupid error has occurred")
except Exception as e:
    the_error = str(e)
    pass

>>> the_error
'A stupid error has occurred'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM