0

I want to return the error in my code that I wrote in python. I can't do this. How can I do it?

def proc():
    try:
        a=2/0
    except Exception as e:
        print("Except")
        raise f"{e}"
    else:
        return "Success"

result=proc()
print("result : ",result)

I tried using direct raise but it didn't work? How can I do?

Jamiu S.
  • 5,257
  • 5
  • 12
  • 34
Ygz Nb
  • 1
  • 1
  • If you want the error to be reported just don't catch it. And you'll get the `ZeroDivisionError` raised inside `proc()`. – 0x0fba Dec 09 '22 at 07:39
  • Don't you just want to return the error? Instead of raising it? – Nineteendo Dec 09 '22 at 07:40
  • Does this answer your question? [python exception message capturing](https://stackoverflow.com/questions/4690600/python-exception-message-capturing) – Patrice Bernassola Dec 09 '22 at 07:41
  • How do you know it didn't work? See how to create a [mcve] and [edit] the question. You used to be able to raise a string literal as an exception in Python 2, but this has been deprecated for a long time, [since 2.5](https://peps.python.org/pep-0352/), and removed in 3.0. – Peter Wood Dec 09 '22 at 07:59
  • What **exactly** do you want to return? Did you notice the TypeError when you tried running this code? Have you looked at the documentation for raise. If not, here it is for your convenience: https://docs.python.org/3/reference/simple_stmts.html#raise – DarkKnight Dec 09 '22 at 08:01

1 Answers1

1

If you just want to return the error message with the class name, you could probably do this:

def proc():
    try:
        a=2/0
    except Exception as e:
        print("Except")
        return repr(e) # Repr is a great solution
    else:
        return "Success"

result=proc()
print("result : ",result)

Result:

Except
result :  ZeroDivisionError(division by zero)
Nineteendo
  • 882
  • 3
  • 18