Bird
Raised Fist0
Pythonprogramming~10 mins

Multiple exception handling in Python - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - Multiple exception handling
Start try block
Code runs
Exception?
v1
Match exception type?
v2
Handle
Continue after try-except
The program tries code, checks if an exception happens, then matches it to multiple except blocks to handle it or lets it propagate.
Execution Sample
Python
try:
    x = int('abc')
except ValueError:
    print('ValueError caught')
except TypeError:
    print('TypeError caught')
This code tries to convert a string to int, catches ValueError or TypeError separately.
Execution Table
StepActionEvaluationResult
1Enter try blockNo exception yetProceed to next line
2Execute x = int('abc')Raises ValueErrorException raised
3Check except ValueErrorMatches exception typeHandle ValueError
4Execute print('ValueError caught')Prints messageOutput: ValueError caught
5Exit try-exceptHandled exceptionContinue program
6EndNo more codeProgram ends
💡 Exception ValueError caught by first except block, program continues normally
Variable Tracker
VariableStartAfter Step 2After Step 5
xundefinedException raised, no assignmentundefined
Key Moments - 2 Insights
Why doesn't the second except block for TypeError run?
Because the exception raised is ValueError, which matches the first except block (see step 3 in execution_table), so Python handles it there and skips the rest.
What happens if no except block matches the exception?
The exception propagates and stops the program unless caught elsewhere. This is shown in the flow where unmatched exceptions go to 'Unhandled -> propagate'.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the output at step 4?
ATypeError caught
BNo output
CValueError caught
DProgram crashes
💡 Hint
Check the 'Result' column at step 4 in the execution_table.
At which step does the program decide which except block to run?
AStep 2
BStep 3
CStep 4
DStep 5
💡 Hint
Look at the 'Action' and 'Evaluation' columns in execution_table step 3.
If the code raised a TypeError instead, which except block would run?
ATypeError except block
BNo except block, program crashes
CValueError except block
DBoth except blocks
💡 Hint
Refer to the except blocks in the code sample and how exceptions match types.
Concept Snapshot
try:
  code that may raise exceptions
except ExceptionType1:
  handle ExceptionType1
except ExceptionType2:
  handle ExceptionType2

Python checks exceptions in order and runs the first matching except block.
Full Transcript
This example shows how Python runs code inside a try block and watches for exceptions. If an exception happens, Python looks at each except block in order to find one that matches the exception type. When it finds a match, it runs that except block's code and then continues the program normally. If no except block matches, the program stops with an error. In the example, converting 'abc' to int raises a ValueError, which is caught by the first except block. The second except block for TypeError is ignored because the exception type does not match. This way, multiple exceptions can be handled separately and clearly.

Practice

(1/5)
1.

What is the purpose of using multiple except blocks after a single try block in Python?

easy
A. To create multiple loops inside the try block
B. To run the same code multiple times
C. To handle different types of errors separately
D. To ignore all errors silently

Solution

  1. Step 1: Understand the role of try-except

    The try block runs code that might cause errors, and except blocks catch those errors.
  2. Step 2: Purpose of multiple except blocks

    Multiple except blocks allow catching different error types separately to handle each properly.
  3. Final Answer:

    To handle different types of errors separately -> Option C
  4. Quick Check:

    Multiple except blocks = handle different errors [OK]
Hint: Multiple except blocks catch different error types separately [OK]
Common Mistakes:
  • Thinking multiple except blocks run all at once
  • Believing except blocks create loops
  • Assuming except blocks ignore errors
2.

Which of the following is the correct syntax to catch both ValueError and TypeError exceptions separately?

try:
    x = int(input())
except ???:
    print("Value error occurred")
except ???:
    print("Type error occurred")
easy
A. except ValueError: except TypeError:
B. except (ValueError, TypeError): except Exception:
C. except ValueError, TypeError: except Exception:
D. except ValueError | TypeError: except Exception:

Solution

  1. Step 1: Check syntax for multiple except blocks

    Each except block must catch one exception type separately using except ExceptionType:.
  2. Step 2: Identify correct syntax

    except ValueError: except TypeError: uses separate except blocks for ValueError and TypeError, which is correct syntax.
  3. Final Answer:

    except ValueError: except TypeError: -> Option A
  4. Quick Check:

    Separate except blocks = except ExceptionType: [OK]
Hint: Use separate except lines for each error type [OK]
Common Mistakes:
  • Using commas or pipes inside except incorrectly
  • Trying to catch multiple exceptions in one except without tuple
  • Using wrong syntax like except ValueError, TypeError:
3.

What will be the output of the following code?

try:
    a = 5 / 0
except ValueError:
    print("Value Error")
except ZeroDivisionError:
    print("Zero Division Error")
else:
    print("No Error")
finally:
    print("Done")
medium
A. Zero Division Error Done
B. Value Error Done
C. No Error Done
D. Zero Division Error

Solution

  1. Step 1: Identify the error raised in try block

    The expression 5 / 0 raises a ZeroDivisionError.
  2. Step 2: Match the except block and output

    The ZeroDivisionError except block runs, printing "Zero Division Error". The finally block always runs, printing "Done".
  3. Final Answer:

    Zero Division Error Done -> Option A
  4. Quick Check:

    ZeroDivisionError caught + finally runs = output A [OK]
Hint: Match error type to except block, finally always runs [OK]
Common Mistakes:
  • Confusing ValueError with ZeroDivisionError
  • Forgetting finally block always runs
  • Expecting else block to run on error
4.

Find the error in this code snippet and choose the correct fix:

try:
    x = int('abc')
except ValueError, TypeError:
    print("Error occurred")
medium
A. Change except line to: except ValueError | TypeError:
B. Change except line to: except (ValueError, TypeError):
C. Change except line to: except ValueError, TypeError:
D. No change needed, code is correct

Solution

  1. Step 1: Identify syntax error in except line

    The syntax except ValueError, TypeError: is invalid for catching multiple exceptions.
  2. Step 2: Correct syntax for multiple exceptions

    Use a tuple of exceptions inside parentheses: except (ValueError, TypeError):.
  3. Final Answer:

    Change except line to: except (ValueError, TypeError): -> Option B
  4. Quick Check:

    Multiple exceptions need parentheses tuple [OK]
Hint: Use parentheses tuple for multiple exceptions in one except [OK]
Common Mistakes:
  • Using commas without parentheses
  • Using pipe | operator incorrectly
  • Assuming original syntax is valid
5.

You want to write a function that tries to convert a string to an integer and then divide 100 by that number. It should handle ValueError if conversion fails, ZeroDivisionError if division by zero happens, and print "Success" if no error occurs, and print "Done" regardless of errors. Which code correctly implements this?

hard
A. def func(s): try: n = int(s) result = 100 / n except ValueError: print("Conversion error") except ZeroDivisionError: print("Division by zero") else: print("Success")
B. def func(s): try: n = int(s) result = 100 / n except (ValueError, ZeroDivisionError): print("Error") finally: print("Success")
C. def func(s): try: n = int(s) result = 100 / n except ValueError: print("Conversion error") except ZeroDivisionError: print("Division by zero") finally: print("Success")
D. def func(s): try: n = int(s) result = 100 / n except ValueError: print("Conversion error") except ZeroDivisionError: print("Division by zero") else: print("Success") finally: print("Done")

Solution

  1. Step 1: Check handling of exceptions and success message

    Function must catch ValueError and ZeroDivisionError separately and print appropriate messages.
  2. Step 2: Check use of else and finally blocks

    else runs only if no exception, so "Success" should be printed there. finally always runs, so "Done" can be printed there.
  3. Step 3: Verify option correctness

    def func(s): try: n = int(s) result = 100 / n except ValueError: print("Conversion error") except ZeroDivisionError: print("Division by zero") else: print("Success") finally: print("Done") correctly uses separate except blocks, prints "Success" in else, and "Done" in finally.
  4. Final Answer:

    Option D code correctly implements all requirements -> Option D
  5. Quick Check:

    Separate except + else for success + finally for done [OK]
Hint: Use else for success, finally for cleanup, separate except blocks [OK]
Common Mistakes:
  • Printing success in finally instead of else
  • Combining exceptions in one except without separate messages
  • Omitting finally block when needed