Challenge - 5 Problems
Exception Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ assertion
intermediate2:00remaining
Correct use of pytest.raises to catch ZeroDivisionError
What will be the result of this test when run with pytest?
PyTest
import pytest def test_divide_by_zero(): with pytest.raises(ZeroDivisionError): x = 1 / 0
Attempts:
2 left
💡 Hint
Remember pytest.raises expects the exact exception type to catch.
✗ Incorrect
The test uses pytest.raises with ZeroDivisionError, which matches the exception raised by dividing by zero, so the test passes.
❓ assertion
intermediate2:00remaining
Detecting wrong exception type in pytest.raises
What happens when this test runs?
PyTest
import pytest def test_value_error(): with pytest.raises(KeyError): int('abc')
Attempts:
2 left
💡 Hint
Check which exception int('abc') actually raises.
✗ Incorrect
int('abc') raises ValueError, but pytest.raises expects KeyError, so the test fails.
❓ Predict Output
advanced2:00remaining
Output of pytest.raises context manager with exception info
What will be the value of 'exc_type' after running this test?
PyTest
import pytest def test_exception_info(): with pytest.raises(ValueError) as exc_info: raise ValueError('Invalid input') exc_type = exc_info.type print(exc_type.__name__)
Attempts:
2 left
💡 Hint
exc_info.type holds the exception class caught by pytest.raises.
✗ Incorrect
The exception raised is ValueError, so exc_info.type is ValueError.
🔧 Debug
advanced2:00remaining
Why does this pytest.raises test fail unexpectedly?
Identify why this test fails even though it seems to catch the exception.
PyTest
import pytest def test_key_error(): with pytest.raises(KeyError): d = {'a': 1} value = d['b'] print('Accessed value:', value)
Attempts:
2 left
💡 Hint
Check where the exception is raised and if the with block covers it.
✗ Incorrect
The KeyError is raised when accessing d['b'], which is inside the with block, so pytest.raises catches it and the test passes.
❓ framework
expert3:00remaining
Using pytest.raises to assert exception message content
Which option correctly asserts that the exception message contains the word 'timeout'?
PyTest
import pytest def test_timeout_error(): with pytest.raises(RuntimeError) as exc_info: raise RuntimeError('Connection timeout occurred') # Assertion here
Attempts:
2 left
💡 Hint
Exception message is accessed via str(exc_info.value).
✗ Incorrect
The exception message is a string representation of exc_info.value, so checking 'timeout' in str(exc_info.value) is correct.