Errors and exceptions theory + first problem: convert a port from text safely
easyErrors and exceptions
Problem statement
An exception is what a program raises when something goes wrong while it runs, such as turning "abc" into a number. If nothing handles it, the program stops right there.
Handling it takes two parts:
- try: the risky code goes here.
- except (Java and C++: catch): what to do if that specific error happens.
Ports often arrive as text from a config file or a command line, so converting them safely matters.
flowchart LR
A["try: convert text"] --> B{"worked?"}
B -->|yes| C["use the number"]
B -->|no| D["except: handle the error"]
C --> E["program continues"]
D --> E
classDef risky fill:#FEF3C7,stroke:#D97706,color:#92400E
classDef check fill:#E0E7FF,stroke:#4F46E5,color:#312E81
classDef good fill:#D1FAE5,stroke:#059669,color:#065F46
classDef bad fill:#FEE2E2,stroke:#DC2626,color:#7F1D1D
class A risky
class B check
class C good
class D bad
class E good
Common mistake: converting without any protection.
TEXT
Wrong:port = int("abc")ValueError: invalid literal for int()The lines after this one never run.Your task: for each of the texts 8080, abc, 443 and port, try to convert it to a number. Print <text> -> <number> if it works, or <text> -> invalid if it does not.
Expected output
◈ DIAGRAM
8080 -> 8080abc -> invalid443 -> 443port -> invalidApproach
Put the conversion in a try block and catch only the error that means "not a number":
- Python:
int(text)raisesValueError. Catch it withexcept ValueError:. - Java:
Integer.parseInt(text)throwsNumberFormatException. Catch it withcatch (NumberFormatException e). - C++:
std::stoi(text)throwsstd::invalid_argument. Catch it withcatch (const std::invalid_argument&).
Catch the specific error, not everything. That way a real bug elsewhere is not hidden.
for text in ["8080", "abc", "443", "port"]:
try:
port = int(text)
print(f"{text} -> {port}")
except ValueError:
print(f"{text} -> invalid")