如何修复"deprecated form of raising 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中给了我"抛出异常的弃用形式"警告。我该怎么修理它?我需要保存原始的异常信息

尝试以这种方式引发异常:

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!

最新更新