A custom exception is a user-defined error type created by subclassing the built-in Exception class. It helps to signal specific error conditions in your code.
Click to reveal answer
beginner
How do you test that a custom exception is raised using pytest?
Use pytest.raises() as a context manager around the code that should raise the exception. Then assert the exception type matches your custom exception.
Click to reveal answer
beginner
Example: Write a pytest snippet to check if MyError is raised when calling func().
import pytest
with pytest.raises(MyError):
func()
Click to reveal answer
intermediate
Why create custom exceptions instead of using built-in exceptions?
Custom exceptions make your error handling clearer and more specific. They help other developers understand what kind of error occurred and allow targeted exception handling.
Click to reveal answer
intermediate
What is the benefit of checking the exception message in tests?
Checking the exception message ensures the error is not only the right type but also triggered for the expected reason, improving test accuracy.
Click to reveal answer
Which pytest function is used to test if a custom exception is raised?
Apytest.expect()
Bpytest.assertRaises()
Cpytest.check_exception()
Dpytest.raises()
✗ Incorrect
pytest.raises() is the correct function to check if an exception is raised in pytest.
How do you define a custom exception in Python?
Aexception MyError: pass
Bdef MyError(): pass
Cclass MyError(Exception): pass
Dclass MyError(): pass
✗ Incorrect
Custom exceptions are defined by subclassing Exception, like 'class MyError(Exception): pass'.
What is the purpose of testing exception messages?
ATo ignore the exception
BTo verify the error reason is correct
CTo improve test speed
DTo check the exception type only
✗ Incorrect
Testing messages confirms the exception was raised for the expected reason.
Which of these is NOT a benefit of custom exceptions?
AAutomatically fixes bugs
BClearer error handling
CMore specific error types
DEasier debugging
✗ Incorrect
Custom exceptions help with clarity and debugging but do not fix bugs automatically.
In pytest, what happens if the expected exception is NOT raised inside pytest.raises()?
AThe test fails
BThe test passes
CThe test is skipped
DThe test is ignored
✗ Incorrect
If the expected exception is not raised, pytest.raises() causes the test to fail.
Explain how to write a pytest test that checks for a custom exception.
Think about how you catch errors in real life and how pytest helps you check for them.
You got /4 concepts.
Why is it useful to create and test custom exceptions in your code?
Consider how specific error messages help you fix problems faster.
You got /4 concepts.
Practice
(1/5)
1. What is the main purpose of using pytest.raises() in testing custom exceptions?
easy
A. To check if a specific exception is raised during a function call
B. To skip a test when an exception occurs
C. To automatically fix exceptions in the code
D. To print the exception message to the console
Solution
Step 1: Understand the role of pytest.raises()
This function is used to verify that a specific exception is raised when running a block of code.
Step 2: Identify the purpose in testing
It helps confirm that error handling works as expected by catching the intended exception type.
Final Answer:
To check if a specific exception is raised during a function call -> Option A
Quick Check:
pytest.raises() checks exceptions [OK]
Hint: Remember: pytest.raises() tests if code throws an error [OK]
Common Mistakes:
Thinking pytest.raises() fixes errors
Using pytest.raises() to skip tests
Expecting pytest.raises() to print messages
2. Which of the following is the correct syntax to test if a function foo() raises a custom exception MyError using pytest?
easy
A. assert pytest.raises(MyError, foo)
B. pytest.raises(MyError, foo())
C. with pytest.raises(MyError): foo()
D. pytest.check_exception(MyError, foo())
Solution
Step 1: Recall pytest.raises() usage
The correct way is to use it as a context manager with with and call the function inside the block.
Step 2: Analyze each option
with pytest.raises(MyError): foo() uses the context manager correctly. Options B and C misuse the function call or assert. pytest.check_exception(MyError, foo()) uses a non-existent function.
Final Answer:
with pytest.raises(MyError): foo() -> Option C
Quick Check:
Use context manager with pytest.raises() [OK]
Hint: Use 'with pytest.raises(Exception):' before calling function [OK]
Common Mistakes:
Calling function inside pytest.raises() without 'with'
Using assert with pytest.raises() incorrectly
Using non-existent pytest functions
3. Given the code below, what will be the test result?
class MyError(Exception):
pass
def func():
raise MyError("Error happened")
def test_func():
with pytest.raises(MyError) as exc_info:
func()
assert str(exc_info.value) == "Error happened"
medium
A. Test raises a syntax error
B. Test fails because the exception type is wrong
C. Test fails because the exception message is incorrect
D. Test passes because the exception and message match
Solution
Step 1: Check exception type raised by func()
func() raises MyError with message "Error happened".
Step 2: Verify test assertions
The test uses pytest.raises(MyError) to catch the exception and asserts the message matches exactly.
Final Answer:
Test passes because the exception and message match -> Option D
Quick Check:
Exception type and message match = pass [OK]
Hint: Match both exception type and message for success [OK]
Common Mistakes:
Ignoring exception message in assertion
Catching wrong exception type
Forgetting to call the function inside the context
4. Identify the error in the following pytest test for a custom exception:
def test_error():
with pytest.raises(ValueError):
raise TypeError("Wrong type")
medium
A. The test will pass because any exception is accepted
B. The test will fail because the raised exception type does not match the expected
C. The test has a syntax error due to missing colon
D. The test will raise an error because ValueError is not imported
Solution
Step 1: Compare expected and raised exceptions
The test expects a ValueError but raises a TypeError instead.
Step 2: Understand pytest.raises() behavior
pytest.raises() fails the test if the raised exception type does not match the expected one.
Final Answer:
The test will fail because the raised exception type does not match the expected -> Option B
Quick Check:
Exception type mismatch causes test failure [OK]
Hint: Expected and raised exception types must match exactly [OK]
Common Mistakes:
Assuming any exception passes the test
Ignoring exception type differences
Confusing syntax errors with logic errors
5. You have a custom exception MyError that can be raised with different messages. How can you write a pytest test that checks the exception is raised and the message contains the word "timeout" regardless of other text?
hard
A. Use with pytest.raises(MyError, match="timeout"): to match substring
B. Use with pytest.raises(MyError) as e: then assert str(e.value) == "timeout"
C. Use assertRaises(MyError, "timeout") to check message
D. Use pytest.raises(MyError, message_contains="timeout")
Solution
Step 1: Recall pytest.raises() match parameter
pytest.raises() accepts a match argument to check if the exception message matches a regex or substring.
Step 2: Compare options for message checking
with pytest.raises(MyError, match="timeout"): correctly uses the match parameter to verify the message contains "timeout". with pytest.raises(MyError) as e: followed by assert str(e.value) == "timeout" only checks for exact match, failing if there is extra text. Options C and D use invalid syntax.
Final Answer:
Use with pytest.raises(MyError, match="timeout"): -> Option A
Quick Check:
Use match parameter to check message substring [OK]
Hint: Use pytest.raises(..., match="text") to check message content [OK]
Common Mistakes:
Using exact match instead of substring check for the message
Using non-existent pytest.raises() parameters
Not checking message content at all
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.