如何修复“弃用的异常形式”警告

时间:2014-06-29 11:15:40

标签: python python-2.7 exception

假设我有以下代码:

import sys
import traceback


class MyException(Exception):
    pass


def bar():
    [][1]


def foo():
    bar()


try:
    try:
        foo()
    except Exception as ex:
        type, value, tb = sys.exc_info()
        raise MyException, ("You did something wrong!", type, value), tb
except LolException:
    print(traceback.format_exc())

它为我提供了PyCharm中“不赞成提出异常”的警告。我该如何解决?我需要保存原始的异常信息。

1 个答案:

答案 0 :(得分:1)

尝试以这种方式提出异常:

import sys
import traceback

class MyException(Exception):
    pass

class LolException(Exception):
    pass

def bar():
    [][1]

def foo():
    bar()

try:
    try:
        foo()
    except Exception as ex:
        raise MyException(str(ex)+" You did something wrong!"), \
                          None, sys.exc_info()[2]
except LolException:
    print(traceback.format_exc())

输出:

Traceback (most recent call last):
  File deprecated.py, line 21, in <module>
    foo()
  File deprecated.py, line 17, in foo
    bar()
  File deprecated.py, line 14, in bar
    [][1]
__main__.MyException: list index out of range You did something wrong!