Convert a port from text safely
Problem statement
Ports read from config files or user input arrive as text. Convert port_text to a number with int(). If it works, print Port: N. If the text is not a valid number, print Invalid port: <text> instead of crashing.
Examples
Example 1
Input: port_text = "80a"
Output: Invalid port: 80a
Hints
Approach
Optimal
Some operations can fail at runtime, and when they do Python raises an exception, which stops the program with a traceback unless you handle it. int("80a") raises ValueError because the text is not a whole number. Wrapping the risky code in a try: block and adding except ValueError: lets you catch that specific error and respond with a clear message. The else: block runs only when no exception happened, keeping the success path separate from the conversion. Catching the specific exception type, rather than everything, means real bugs elsewhere still show up.
port_text = "80a" try: port = int(port_text)except ValueError: print(f"Invalid port: {port_text}")else: print(f"Port: {port}")Follow-up questions
- Also reject numbers outside 1 to 65535 with a separate message.
- Loop over a list of port strings and print the valid ones.
Frequently asked questions
A bare except: catches every error, including typos in your own code and Ctrl+C. It hides bugs. Catch only the exceptions you expect and know how to handle.