Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

How to catch ValueError using Exception in Python?

If I try to run the following line of code, I get an error

n = int('magnolia')

How do I handle this error and find its type?


1 Answer
Manogna

A ValueError is used when a function receives a value that has the right type but an invalid value.

The given code can be rewritten as follows to handle the exception and find its type.

import sys
try:
n = int('magnolia')
except Exception as e:
print e
print sys.exc_type

OUTPUT

invalid literal for int() with base 10: 'magnolia'
<type 'exceptions.ValueError'>
Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.