Catching exceptions
- Python course
- Intermediate
- Lesson 109/116
- 4 min
Learn to catch exceptions in __exit__.
Catching exceptions in a context manager
The __exit__ method can catch errors inside the block. If it returns True the error is suppressed:
class Koruyucu:
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type is not None:
print("hata yakalandı")
return True
with Koruyucu():
raise ValueError("test")
# hata yakalandıHere raise ValueError is raised inside the with block. __exit__ detects it via exc_type and suppresses it by returning True. The program does not crash.
This is useful for temporary error suppression.
Difference between return True and False
If __exit__ returns True the error does not propagate outside the with block — as if it were caught. If it returns False or None the error propagates normally:
# True: error suppressed
# False/None: error propagatesThis is similar to an except block in try/except. But in a context manager the suppression is done inside __exit__.
Use carefully — hiding unexpected errors is dangerous.
Practice Suppress an error with Koruyucu
Define class Koruyucu:. In __enter__ write return self. In __exit__ write if exc_type is not None: print("hata yakalandı"); return True. Inside a with Koruyucu(): block write raise ValueError("test").
Starter code
# write the Koruyucu class
# catch and suppress the error in __exit__Sample solution
class Koruyucu:
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type is not None:
print("hata yakalandı")
return True
with Koruyucu():
raise ValueError("test")Expected output
hata yakalandı
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does exc_type being None in __exit__ mean?
- An error occurred
- No error occurred Correct answer
- The program crashed
- The error was suppressed
Explanation: If exc_type is None there was no error in the block.
2 Match exception catching
| Term | Meaning |
|---|---|
exc_type |
Error type |
exc_val |
Error value |
return True |
Suppress error |
return None |
Propagate error |
3 Complete the __exit__ signature
def __exit__(self, ____, exc_val, exc_tb):
def __exit__(self, exc_type, exc_val, exc_tb):
Explanation: exc_type carries the error type.