Menu
CoddyTech

Validation and Exceptions

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

GDScript has no Python-style try/except exception handling. Godot code often validates text with is_valid_int before converting or reports failure through a result value. Python int raises ValueError on malformed integer text, which a specific except clause can handle. A successful parse still needs range checking. Python with manages resources through a context-manager protocol rather than engine object lifetime.

GDScript

extends SceneTree
func _init():
    var text = "12cats"
    if text.is_valid_int():
        print(int(text))
    else:
        print("invalid")
    quit()

Python

try:
    print(int("12cats"))
except ValueError:
    print("invalid")

Porting trap

Do not translate push_error into raise without deciding whether the caller must recover. Logging an engine error and throwing a Python exception have different control-flow effects.

Complete the task in its editable modules. The locked driver.py supplies execution; keep the required API names.

challenge icon

Challenge

Beginner

Implement parse_capacity(text). Convert the string with int. Accept integers from 0 through 500, inclusive, and return the integer. Raise ValueError for malformed text or out-of-range values. Do not print or read input. The driver reads one line, prints the returned capacity, or prints invalid when ValueError is raised. Surrounding whitespace and a leading plus sign are allowed by integer conversion.

The locked driver also calls your function with invalid arguments to verify the required exceptions. A successful result must be an integer; returning error text does not satisfy the contract. These checks produce no additional output.

Your function definitions go in functions.py. The locked driver.py imports them and handles the supplied input/output and checks. You do not need to edit the driver.

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 GDScript Developers

Practice on your own: Online Python compiler