Catch Multiple Exceptions Without Parentheses in Python 3.14

Catch Multiple Exceptions Without Parentheses in Python 3.14

The except clause in Python is used to handle runtime errors. It allows developers to catch one or more exception types and respond appropriately when something goes wrong. Since Python 3.14, the syntax for handling multiple exceptions has been simplified. We no longer need to wrap exception types in parentheses when listing more than one.

Consider a simple case where a program attempts to open and read a file that may not exist or may lack the required permissions. Before Python 3.14, catching multiple exceptions required grouping them inside parentheses. This was the only valid way to specify more than one exception type in a single except block.

try:
    with open('not_exist.txt') as file:
        print(file.read())
except (FileNotFoundError, PermissionError):
    print('File access error')

Since Python 3.14, multiple exceptions can now be listed directly, separated by commas, without enclosing them in parentheses.

try:
    with open('not_exist.txt') as file:
        print(file.read())
except FileNotFoundError, PermissionError:
    print('File access error')

This enhancement reduces visual clutter and makes exception handling easier to read and write.

Leave a Comment

Cancel reply

Your email address will not be published.