Skip to main content
Programming from zero

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 -> 8080
abc -> invalid
443 -> 443
port -> invalid

Approach

Put the conversion in a try block and catch only the error that means "not a number":

  • Python: int(text) raises ValueError. Catch it with except ValueError:.
  • Java: Integer.parseInt(text) throws NumberFormatException. Catch it with catch (NumberFormatException e).
  • C++: std::stoi(text) throws std::invalid_argument. Catch it with catch (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")