Use a function to convert input and handle the expected conversion error.
Python code
def parse_port(text):
port = int(text)
if not 1 <= port <= 65535:
raise ValueError('Port out of range')
return port
try:
print(parse_port('8080'))
except ValueError as error:
print(error)
Practical useValidate a demo service port before storing it.
Common mistakesAvoid a bare except; it can hide unrelated failures. Do not print private exception details in a public API.