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?

5
  • If you want the error to be reported just don't catch it. And you'll get the ZeroDivisionError raised inside proc(). Commented Dec 9, 2022 at 7:39
  • Don't you just want to return the error? Instead of raising it? Commented Dec 9, 2022 at 7:40
  • Does this answer your question? python exception message capturing Commented Dec 9, 2022 at 7:41
  • How do you know it didn't work? See how to create a minimal reproducible example 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, and removed in 3.0. Commented Dec 9, 2022 at 7: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: docs.python.org/3/reference/simple_stmts.html#raise Commented Dec 9, 2022 at 8:01

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.