Ygz Nb
Ygz Nb

Reputation: 1

How do i return error in exception in python?

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?

Upvotes: 0

Views: 555

Answers (1)

Nice Zombies
Nice Zombies

Reputation: 1087

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)

Upvotes: 1

Related Questions