python

Get exception text in python

To get the exception text thrown by python code, you can use the below code.

try:
  result = 3/0 #this will throw error
  
except Exception as e:
  print("Repr : " + repr(e)) # Use repr to get error
  print("Error : " + str(e)) # Use str to get error
Output
Repr : ZeroDivisionError('division by zero',)
Error : division by zero

We are getting exception thrown by dividing a number by 0. We are using repr and str to print out the exception text.

Was this helpful?