Browse topics

Handling exceptions

Version
3.14
Review
Draft

Summary#

except handles matching exceptions, else runs when control reaches the end of the try block normally, and finally runs on the way out. raise ... from records the original exception as the cause of a new one.

Syntax#

python
try:
    action()
except (ValueError, TypeError) as error:
    raise AppError("action failed") from error
else:
    succeeded()
finally:
    cleanup()

Example#

python
class ConfigError(Exception):
    pass


def parse_port(raw):
    try:
        port = int(raw)
    except ValueError as error:
        raise ConfigError(f"invalid port: {raw!r}") from error
    else:
        return port
    finally:
        print("checked", raw)


print(parse_port("8080"))
try:
    parse_port("http")
except ConfigError as error:
    print(error)
    print(type(error.__cause__).__name__)

Expected output#

Text
checked 8080
8080
checked http
invalid port: 'http'
ValueError

Common mistakes#

A bare except: also catches KeyboardInterrupt and SystemExit, which do not derive from Exception. Catch the specific types you can handle. A return, break or continue that exits finally discards a pending exception.

Version applicability#

The parenthesized except with as and raise ... from work on all Python 3 releases. The example needs Python 3.6 for the f-string. Python 3.14 allows except ValueError, TypeError: when there is no as clause. CPython 3.14 also emits a SyntaxWarning for return, break or continue that exits a finally block.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0