Bird
Raised Fist0
PyTesttesting~20 mins

Testing multiple exceptions in PyTest - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Multiple Exceptions Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of pytest test with multiple exception checks
What is the test result when running this pytest test function that checks for multiple exceptions?
PyTest
import pytest

def func(x):
    if x == 0:
        raise ValueError("Zero not allowed")
    elif x == 1:
        raise TypeError("One is wrong type")
    return x

def test_func_exceptions():
    with pytest.raises(ValueError):
        func(0)
    with pytest.raises(TypeError):
        func(1)
ATest passes but does not catch any exceptions.
BTest passes with both exceptions correctly caught.
CTest fails because only the first exception is caught; second raises an error.
DTest fails due to a SyntaxError in the test code.
Attempts:
2 left
💡 Hint
pytest.raises can be used multiple times in one test function to check different exceptions.
❓ assertion
intermediate
2:00remaining
Correct assertion to check multiple exceptions in pytest
Which assertion correctly tests that a function raises either ValueError or TypeError when called with certain inputs?
PyTest
def func(x):
    if x == 0:
        raise ValueError("Zero not allowed")
    elif x == 1:
        raise TypeError("One is wrong type")
    return x
A
with pytest.raises(ValueError):
    func(0)
with pytest.raises(TypeError):
    func(1)
B
with pytest.raises((ValueError, TypeError)):
    func(0)
    func(1)
C
with pytest.raises(ValueError) or pytest.raises(TypeError):
    func(0)
    func(1)
Dassert func(0) raises ValueError and func(1) raises TypeError
Attempts:
2 left
💡 Hint
Use separate pytest.raises blocks for different exceptions.
🔧 Debug
advanced
2:00remaining
Debug why second exception test is not reached
Why does the second exception test not run in this pytest code?
PyTest
import pytest

def func(x):
    if x == 0:
        raise ValueError("Zero not allowed")
    elif x == 1:
        raise TypeError("One is wrong type")
    return x

def test_func():
    with pytest.raises((ValueError, TypeError)):
        func(0)
        func(1)
ABecause the test function is missing a return statement.
BBecause pytest.raises cannot catch multiple exceptions in one block.
CBecause func(1) does not raise any exception.
DBecause func(0) raises ValueError and exits the with block before func(1) is called.
Attempts:
2 left
💡 Hint
Consider how exceptions interrupt code flow inside a with block.
❓ framework
advanced
2:00remaining
Best pytest pattern to test multiple exceptions separately
Which pytest test function correctly tests that func raises ValueError for 0 and TypeError for 1, ensuring both exceptions are tested independently?
PyTest
def func(x):
    if x == 0:
        raise ValueError("Zero not allowed")
    elif x == 1:
        raise TypeError("One is wrong type")
    return x
A
def test_func():
    with pytest.raises(ValueError):
        func(0)
    with pytest.raises(TypeError):
        func(1)
B
def test_func():
    with pytest.raises((ValueError, TypeError)):
        func(0)
        func(1)
C
def test_func():
    assert func(0) raises ValueError
    assert func(1) raises TypeError
D
def test_func():
    try:
        func(0)
    except ValueError:
        pass
    try:
        func(1)
    except TypeError:
        pass
Attempts:
2 left
💡 Hint
Use separate with blocks for each exception test.
🧠 Conceptual
expert
2:00remaining
Why separate pytest.raises blocks are preferred for multiple exceptions
Why is it better to use separate pytest.raises blocks when testing multiple exceptions in one test function?
ABecause combining exceptions in one block causes syntax errors.
BBecause pytest.raises only supports one exception type per test file.
CBecause each pytest.raises block stops execution on exception, so separate blocks ensure all exceptions are tested.
DBecause pytest.raises automatically retries the block until all exceptions occur.
Attempts:
2 left
💡 Hint
Think about how exceptions affect code flow inside a with block.

Practice

(1/5)
1. What does pytest.raises((ValueError, TypeError)) do in a test?
easy
A. It passes if either ValueError or TypeError is raised during the test.
B. It passes only if both ValueError and TypeError are raised together.
C. It fails if any exception is raised during the test.
D. It ignores exceptions and always passes the test.

Solution

  1. Step 1: Understand pytest.raises with tuple

    Using a tuple inside pytest.raises means the test expects any one of those exceptions.
  2. Step 2: Effect on test pass/fail

    If the code raises either ValueError or TypeError, the test passes. If no exception or a different exception is raised, it fails.
  3. Final Answer:

    It passes if either ValueError or TypeError is raised during the test. -> Option A
  4. Quick Check:

    pytest.raises with tuple = any exception in tuple passes [OK]
Hint: Tuple in pytest.raises means any listed exception passes [OK]
Common Mistakes:
  • Thinking both exceptions must be raised simultaneously
  • Assuming it passes without exceptions
  • Confusing tuple with multiple separate pytest.raises calls
2. Which of the following is the correct syntax to test for multiple exceptions in pytest?
easy
A. with pytest.raises{ValueError, TypeError}:
B. with pytest.raises(ValueError, TypeError):
C. with pytest.raises([ValueError, TypeError]):
D. with pytest.raises((ValueError, TypeError)):

Solution

  1. Step 1: Recall pytest.raises syntax

    pytest.raises expects a single exception or a tuple of exceptions inside parentheses.
  2. Step 2: Identify correct tuple syntax

    Only with pytest.raises((ValueError, TypeError)): uses a tuple (parentheses with comma-separated exceptions) correctly.
  3. Final Answer:

    with pytest.raises((ValueError, TypeError)): -> Option D
  4. Quick Check:

    Tuple syntax with parentheses and comma = correct [OK]
Hint: Use parentheses and comma for multiple exceptions in pytest.raises [OK]
Common Mistakes:
  • Using multiple arguments without tuple
  • Using list brackets instead of tuple
  • Using curly braces which are invalid syntax
3. What will be the result of this pytest test?
def test_func():
    with pytest.raises((KeyError, IndexError)):
        d = {'a': 1}
        value = d['b']
medium
A. Test fails due to syntax error.
B. Test passes because KeyError is raised.
C. Test passes because IndexError is raised.
D. Test fails because no exception is raised.

Solution

  1. Step 1: Identify exception raised by d['b']

    Accessing a missing key in a dictionary raises KeyError.
  2. Step 2: Check if KeyError is in the tuple

    KeyError is in (KeyError, IndexError), so pytest.raises expects it and test passes.
  3. Final Answer:

    Test passes because KeyError is raised. -> Option B
  4. Quick Check:

    Missing dict key = KeyError, in tuple = pass [OK]
Hint: Missing dict key raises KeyError, matches tuple exceptions [OK]
Common Mistakes:
  • Thinking IndexError is raised instead
  • Assuming no exception is raised
  • Confusing KeyError with ValueError
4. What will be the result of this pytest test?
def test_divide():
    with pytest.raises((ZeroDivisionError, ValueError)):
        result = 10 / 0
        int('abc')
medium
A. The test will pass because ZeroDivisionError is raised first.
B. The test will fail because the second line after exception is unreachable.
C. The test will fail because only ZeroDivisionError is raised, not ValueError.
D. The test will fail due to syntax error in pytest.raises.

Solution

  1. Step 1: Analyze exception flow in with block

    ZeroDivisionError occurs at 10 / 0, so the next line int('abc') is never executed.
  2. Step 2: Understand pytest.raises behavior

    ZeroDivisionError is in the expected tuple, so test passes. ValueError is unreachable.
  3. Step 3: Confirm test outcome

    Since a matching exception (ZeroDivisionError) is raised first, the test passes.
  4. Final Answer:

    The test will pass because ZeroDivisionError is raised first. -> Option A
  5. Quick Check:

    Exception stops code, later lines unreachable; matching exc = pass [OK]
Hint: Exception stops code; lines after are not run [OK]
Common Mistakes:
  • Thinking both exceptions must be raised simultaneously
  • Thinking test fails due to syntax
  • Ignoring unreachable code after exception
5. You want to test a function that can raise either IndexError or KeyError depending on input. Which pytest test code correctly checks both exceptions in one test?
hard
A. def test_func(): with pytest.raises(IndexError, KeyError): func_that_raises()
B. def test_func(): with pytest.raises([IndexError, KeyError]): func_that_raises()
C. def test_func(): with pytest.raises((IndexError, KeyError)): func_that_raises()
D. def test_func(): with pytest.raises({IndexError, KeyError}): func_that_raises()

Solution

  1. Step 1: Recall correct syntax for multiple exceptions

    pytest.raises expects a tuple of exceptions to check multiple exceptions in one block.
  2. Step 2: Identify correct tuple usage

    def test_func(): with pytest.raises((IndexError, KeyError)): func_that_raises() uses a tuple (parentheses with comma-separated exceptions), which is correct syntax.
  3. Step 3: Check other options

    Options A, B, and D use invalid syntax: multiple arguments without tuple, list, or set instead of tuple.
  4. Final Answer:

    def test_func(): with pytest.raises((IndexError, KeyError)): func_that_raises() -> Option C
  5. Quick Check:

    Tuple of exceptions in pytest.raises = correct [OK]
Hint: Use tuple (parentheses, commas) for multiple exceptions in pytest.raises [OK]
Common Mistakes:
  • Passing exceptions as separate arguments
  • Using list or set instead of tuple
  • Forgetting parentheses around exceptions
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard