Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

Error handling

An exception interrupts normal evaluation and searches outward for the first matching except clause.

Version: Python 3.14; repository image, production runtime not attested

Syntax

try:
    result = int(text)
except ValueError:
    recover()
else:
    use(result)
finally:
    cleanup()

An exception interrupts normal evaluation and searches outward for the first matching except clause.

A handler for a base class also accepts its subclasses. else runs on normal completion of try, and finally runs when control leaves the construct, including propagation. A bare raise re-raises the active exception.

int('8') leads to [8, 'done'], while int('x') leads to ['invalid', 'done'].

class BadInput(ValueError): pass
seen=[]
try:
    try: raise BadInput('x')
    except ValueError: seen.append('handled'); raise
    finally: seen.append('cleanup')
except BadInput: seen.append('caller')
assert seen==['handled','cleanup','caller']
try: compile('if :', '', 'exec')
except SyntaxError: pass
else: raise AssertionError

Examples

def parse(text):
    events = []
    try:
        n = int(text)
    except ValueError:
        events.append("invalid")
    else:
        events.append(n)
    finally:
        events.append("done")
    return events

print(parse("8"), parse("x"))

Result

[8, 'done'] ['invalid', 'done']

int('8') leads to [8, 'done'], while int('x') leads to ['invalid', 'done'].

Sources