How to 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: 12-Jun-2020

258 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements