Sponsored Reserved space — layout preview until AdSense is connected

Try/except ValueError

Convert user input to int inside try/except and show a friendly message.

7 lines 3 views 0 copies Updated May 23, 2026
Try in editor

How it works

int() raises ValueError when the string is not a valid integer. Catch it near the conversion, not at the top of the program.

Give users actionable feedback — say what went wrong and what format you expect.

Avoid bare except: — catch specific exceptions so real bugs still surface.

Python
Try in editor
raw = "42"

try:
    value = int(raw)
    print(f"Parsed: {value}")
except ValueError:
    print(f"Could not parse {raw!r} as an integer.")

Sponsored

Sponsored Reserved space — layout preview until AdSense is connected

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Errors & debugging