Intermediate Chapter 112 · 25 min read · Module 9: Exception Handling
Multiple Except Blocks
- After this chapter you can write several except blocks after one try.
- You can group exception types in a tuple to share one handler.
- You can explain why the order of except blocks matters.
- You can describe how Exception, LookupError and ArithmeticError relate to specific exceptions.
- You can use a final except Exception block as a safety net.
A single piece of code can fail in more than one way. Think of a function that reads a number from a list of text values and divides 100 by it. The text may not be a number, the list position may not exist, or the number may be zero. Each problem deserves its own message, and Python lets you write a separate except block for each one.
When you have several except blocks, Python checks them from top to bottom and runs the first one that matches. This simple rule has an important consequence: the order of your blocks matters. A general handler placed too early will hide the more specific ones below it.
This chapter shows how to write multiple except blocks, how to share a handler between related errors, and how the family tree of exceptions decides which handler wins.
More than one except block
You may follow a single try with as many except blocks as you need. Each block names a different exception type. When an error occurs, Python walks through the blocks in order and runs only the first one whose type matches the error. The others are skipped.
def divide_item(values, position):
try:
number = int(values[position])
return 100 / number
except IndexError:
return 'no such position'
except ValueError:
return 'not a number'
except ZeroDivisionError:
return 'cannot divide by zero'
data = ['4', 'x', '0']
print(divide_item(data, 0))
print(divide_item(data, 1))
print(divide_item(data, 2))
print(divide_item(data, 9))Each call goes wrong, or does not, in a different way. The first one succeeds, so no handler runs. The other three each land in the handler that fits. Only one handler ever runs for a single error.
Sharing one handler
Sometimes two errors need the same response. Instead of repeating code, put the types in a tuple inside one except line. The handler runs if the error matches any type in the tuple.
def read_number(text):
try:
return int(text)
except (ValueError, TypeError) as error:
print('Could not convert:', type(error).__name__)
return None
print(read_number('8'))
print(read_number('eight'))
print(read_number(None))except ValueError, TypeError: was Python 2 style and is not the grouping syntax you want here.The exception family tree
Exceptions are classes, and they are organised into a hierarchy. At the top of the ones you will catch is Exception. Below it are groups. For example, ZeroDivisionError belongs to the group ArithmeticError. Both IndexError and KeyError belong to the group LookupError. Catching a parent type also catches all its children.
| Parent | Children (examples) |
|---|---|
| Exception | almost every error you handle |
| ArithmeticError | ZeroDivisionError, OverflowError |
| LookupError | IndexError, KeyError |
| OSError | FileNotFoundError, PermissionError |
def lookup(container, key):
try:
return container[key]
except LookupError as error:
return 'lookup failed: ' + type(error).__name__
print(lookup([1, 2], 5))
print(lookup({'a': 1}, 'b'))
print(lookup({'a': 1}, 'a'))One LookupError handler serves both lists and dictionaries, because IndexError and KeyError are its children. The printed class name still shows the real error.
Order matters
Because Python picks the first matching block, always list specific types before general ones. If you write except Exception: first, nothing below it can ever run, since every ordinary error is an Exception. Python does not warn you about this in simple cases, so the mistake can sit quietly in your code.
def check(value):
try:
return 10 / value
except ZeroDivisionError:
return 'zero'
except TypeError:
return 'wrong type'
except Exception as error:
return 'other: ' + type(error).__name__
print(check(2))
print(check(0))
print(check('a'))The last block is a safety net for anything unexpected. In real programs it is often used to record the problem. During learning, it is better to let unexpected errors show themselves, so use a final except Exception sparingly.
Choosing your handlers
A good rule is to write a handler only for errors you can respond to. Think about what the code can really do: ask again, use a default, skip an item, or show a helpful message. If you have nothing useful to do, do not catch it. Use one block when the response is the same and several blocks when each problem needs different words or actions.
Seeing the hierarchy for yourself
You do not have to trust a table. Python can tell you the parents of any exception class through its __mro__ attribute, which lists the class followed by every parent in order. Reading it is a quick way to understand why a parent handler catches a child error. It is also useful when you meet an exception you have never seen and want to know which broad group it belongs to.
for cls in (KeyError, ZeroDivisionError, FileNotFoundError):
names = [c.__name__ for c in cls.__mro__]
print(' -> '.join(names))Every chain ends with BaseException and object. The class just before them, Exception, is the one most handlers use as a general safety net. Notice how each chain passes through its group name, such as LookupError for KeyError. That is why a handler for the group can stand in for all its children.
Python syntax
try:
code
except TypeOne:
handler_one
except TypeTwo:
handler_twotry:
code
except (TypeOne, TypeTwo) as error:
shared_handlerReal-world applications
- Giving different help messages for bad input, missing data and invalid math.
- Reading files where a missing file and a permission problem need different responses.
- API clients that treat timeouts and bad data differently.
- Batch scripts that count each kind of failure separately.
Common mistakes
Fix: Put specific exceptions first and general ones last.
Fix: Group types in a tuple: except (ValueError, TypeError):
Fix: Only the first matching block runs for each error.
Fix: Choose the narrowest type that matches the problem you can handle.
Important tips
- List specific exceptions before general ones.
- Use a tuple to share one handler.
- Print type(error).__name__ to see which error you really got.
- Keep a final broad handler only when you will log or report the error.
Key points summary
- One try can have many except blocks.
- Python runs the first matching block only.
- A tuple groups several types in one handler.
- Parent exception types also catch their children.
- Order handlers from specific to general.
Exam and interview points
- The first matching except block runs and the others are skipped.
- IndexError and KeyError are subclasses of LookupError.
- ZeroDivisionError is a subclass of ArithmeticError.
- except (A, B): matches either type.
- A general handler before a specific one makes the specific one unreachable.
Quick revision
- Many except blocks are allowed.
- First match wins.
- Group types with a tuple.
- Parents catch children.
- Specific first, general last.
Frequently asked questions
Can two except blocks run for the same error?
No. Python stops at the first block that matches, and the rest are skipped.
How do I know which exceptions a function can raise?
Read its documentation, and also try it with bad input to see the traceback. Beginners learn many names from experience.
Is catching Exception the same as a bare except?
Almost. Exception does not include a few special exit signals such as KeyboardInterrupt, so it is safer than a bare except.
Why group types in parentheses?
The parentheses make a tuple, which is how Python accepts several types in one except clause.
Does the order matter for unrelated types?
Not for correctness, but it matters whenever one type is a parent of another.
Practise this chapter
21 practice questions Take the chapter quiz