Catch ValueError Using Exception in Python



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.

Example

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'>
Updated on: 2020-06-12T07:56:10+05:30

326 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements