Programming Search⌘K

Featureintro

Handling Exceptions

Also called try except, except clause, catching exceptions, try statement, except as, else clause of try.

A try statement runs its try clause, and when an exception occurs it runs the first except clause that matches the exception type. An optional else clause runs only when no exception occurred.

Language
Python

Synopsis

for text in ['12', 'twelve', '7']:
    try:
        n = int(text)
    except ValueError:
        print('not a number:', text)
    else:
        print('square:', n * n)
Output
square: 144
not a number: twelve
square: 49

When int raises ValueError, the except clause runs. When it does not, the else clause runs.

Semantics

r1. "First, the try clause (the statement(s) between the try and except keywords) is executed. If no exception occurs, the except clause is skipped and execution of the try statement is finished."1 "If an exception occurs during execution of the try clause, the rest of the clause is skipped. Then, if its type matches the exception named after the except keyword, the except clause is executed, and then execution continues after the try/except block."1

r2. "If an exception occurs which does not match the exception named in the except clause, it is passed on to outer try statements; if no handler is found, it is an unhandled exception and execution stops with an error message."1 "Exception handlers do not handle only exceptions that occur immediately in the try clause, but also those that occur inside functions that are called (even indirectly) in the try clause."1 Example: called.

r3. "A try statement may have more than one except clause, to specify handlers for different exceptions. At most one handler will be executed."1 The search "inspects the except clauses in turn until one is found that matches the exception."2 "The raised exception matches an except clause whose expression evaluates to the class or a non-virtual base class of the exception object, or to a tuple that contains such a class."2 Example: several.

r4. "An expression-less except clause, if present, must be last; it matches any exception."2 Example: bare.

r5. "When an exception has been assigned using as target, it is cleared at the end of the except clause."2 "This means the exception must be assigned to a different name to be able to refer to it after the except clause."2 Example: cleared.

r6. The else clause "is executed if the control flow leaves the try suite, no exception was raised, and no return, continue, or break statement was executed. Exceptions in the else clause are not handled by the preceding except clauses."2 "The use of the else clause is better than adding additional code to the try clause because it avoids accidentally catching an exception that wasn’t raised by the code being protected by the try … except statement."1

r7. "Parentheses can be dropped if multiple exception types are provided and the as clause is not used."2 This form is new: "Changed in version 3.14: Support for optionally dropping grouping parentheses when using multiple exception types."2 Before 3.14, except A, B: is a SyntaxError. Example: no-parens.

r8. "Before an except clause’s suite is executed, the exception is stored in the sys module, where it can be accessed from within the body of the except clause by calling sys.exception()."2

Examples

def ratio(a, b):
    return a / b

def report(a, b):
    return f'{ratio(a, b):.2f}'

try:
    print(report(1, 4))
    print(report(1, 0))
except ZeroDivisionError as err:
    print('Handling run-time error:', err)
Output
0.25
Handling run-time error: division by zero

The exception comes from ratio, two calls down, and the handler around the call catches it (rule r2).

def convert(value):
    try:
        return int(value)
    except (TypeError, ValueError) as err:
        return f'{type(err).__name__}: {err}'
    except OverflowError:
        return 'too large'

print(convert('5'))
print(convert(None))
print(convert('x'))
print(convert(float('inf')))
Output
5
TypeError: int() argument must be a string, a bytes-like object or a real number, not 'NoneType'
ValueError: invalid literal for int() with base 10: 'x'
too large

A tuple in an except clause matches any of its classes (rule r3).

try:
    int('x')
except TypeError, ValueError:
    print('bad value')
Output
bad value

On 3.14 and later the parentheses are optional when there is no as (rule r7).

import sys

try:
    [][0]
except IndexError:
    print(repr(sys.exception()))
print(sys.exception())
Output
IndexError('list index out of range')
None

Inside the handler sys.exception() gives the exception, and after the handler it is None (rule r8).

Pitfalls

A bare except: also catches KeyboardInterrupt:

This code runs but gives a wrong answer on purpose.

def work():
    raise KeyboardInterrupt  # what Control-C does

for attempt in range(3):
    try:
        work()
    except:
        print('failed, try again')
Output
failed, try again
failed, try again
failed, try again

The user presses Control-C to stop the program, and the loop goes on. A bare except matches any exception (rule r4). KeyboardInterrupt "inherits from BaseException so as to not be accidentally caught by code that catches Exception and thus prevent the interpreter from exiting."3 Write except Exception:, or name the exact types.

The name after as is deleted after the clause:

This code raises NameError, on purpose.

try:
    int('x')
except ValueError as err:
    print('failed')
print(err)

The last line raises NameError, because Python deletes err at the end of the except clause (rule r5). Assign the exception to another name inside the clause if you need it later.

The Python 2 form except ValueError, e: does not bind e:

This code raises NameError, on purpose.

try:
    int('x')
except ValueError, e:
    print('caught', e)

On 3.14 and later this parses as a clause with two types, ValueError and e (rule r7). When the ValueError occurs, Python evaluates the tuple, e is not defined, and a NameError replaces the ValueError. On 3.13 and older it is a SyntaxError. Write except ValueError as e:.

Comparison

Go has no try statement. Effective Go says: "Library routines must often return some sort of error indication to the caller."4 The caller tests the returned error value with an if statement, so each call has its own check. A Python handler covers all of its try clause and the functions that it calls (rule r2).

References

  1. The Python Tutorial, 8. Errors and Exceptions, 8.3. Handling Exceptions
  2. The Python Language Reference, 8. Compound statements, 8.4. The try statement; 8.4.1. except clause; 8.4.3. else clause
  3. Built-in Exceptions, KeyboardInterrupt
  4. Effective Go, Errors

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source