FrozenHeart
FrozenHeart

Reputation: 20746

How to fix "deprecated form of raising exception" warning

Suppose that I have the following code:

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())

It gives me the "deprecated form of raising exception" warning in PyCharm. How can I fix it? I need to save the original exception info.

Upvotes: 0

Views: 733

Answers (1)

martineau
martineau

Reputation: 123473

Try raising the exception this way:

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())

Output:

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!

Upvotes: 2

Related Questions