Menu
CoddyTech

Errors Versus Exceptions

Lesson 28 of 48 in Coddy's Python for Go Developers course.

Go conventionally returns a value and an error, and the caller explicitly checks err. Python int raises ValueError for malformed numeric text, transferring control to a matching except handler. Signal domain rejection with raise ValueError(...), and catch it at the boundary that can report or recover. TypeError describes an unsupported type or operation, not ordinary malformed numeric text. Python exceptions propagate through calls until handled.

Go

Go excerpt inside main; imports: fmt, strconv. The verification bundle contains the complete program.

// Inside main:
for _, text := range []string{"12", "oops"} {
    n, err := strconv.Atoi(text)
    if err != nil { fmt.Println("invalid"); continue }
    fmt.Println(n)
}

Python

for text in ["12", "oops"]:
    try:
        n = int(text)
    except ValueError:
        print("invalid")
        continue
    print(n)

Porting trap

Do not translate (value, error) into a tuple unless that is the requested Python API. The task requires an integer on success and a raised ValueError on rejection. Go panic/recover is not the usual substitute for ordinary returned errors.

challenge icon

Challenge

Beginner

Implement parse_capacity(text), using int conversion and accepting 0..500 inclusive. Return an int or raise ValueError for malformed strings and out-of-range numbers. Whitespace and a leading plus sign are valid. The driver handles printing and checks error behavior separately without more input. A Go parser might return (value, error); this Python API returns an integer or raises ValueError, never an error tuple or string.

Editable files: functions.py. Keep the provided imports and the required API names. The locked driver.py supplies execution and checks; do not edit it.

Implement the named definitions in the editable modules without input or printing. The driver owns input/output and may call the APIs again on fresh data without producing extra output.

Try it yourself

from functions import parse_capacity

_coddy_line = input()
try:
    _coddy_result = parse_capacity(_coddy_line)
except ValueError:
    print("invalid")
else:
    if type(_coddy_result) is not int:
        raise AssertionError("parse_capacity must return an integer on success")
    print(_coddy_result)
for _coddy_invalid in ("oops", "-1", "501"):
    try:
        parse_capacity(_coddy_invalid)
    except ValueError:
        pass
    else:
        raise AssertionError("parse_capacity must raise ValueError for invalid input")
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Python for Go Developers

Practice on your own: Online Python compiler