Summary - Error handling
- Python course
- Beginner
- Lesson 105/116
- 5 min
Combine try/except/finally and a custom exception to write a bank account class.
Summary - Error handling
In this group you learned five core tools:
- try/except — catches errors
- else/finally — success and cleanup blocks
- raise — throws errors
- Exception hierarchy — BaseException → Exception → subclasses
- Custom exception — a class derived from Exception
Now you will do two short tasks that combine them: one with raise and multiple except, one with a custom exception.
Practice raise and multiple except
Inside a try: block write raise TypeError("tür hatası"). Inside an except ValueError: block write print("değer"). Inside an except TypeError: block write print("tür").
Starter code
# raise TypeError
# write separate except for ValueError and TypeErrorSample solution
try:
raise TypeError("tür hatası")
except ValueError:
print("değer")
except TypeError:
print("tür")Expected output
tür
Practice Define and catch a custom exception
Define class UygulamaError(Exception): with pass in the body. Inside a try: block write raise UygulamaError("hata oluştu"). Inside an except UygulamaError as e: block write print(e).
Starter code
# derive UygulamaError from Exception
# raise it and catch with exceptSample solution
class UygulamaError(Exception):
pass
try:
raise UygulamaError("hata oluştu")
except UygulamaError as e:
print(e)Expected output
hata oluştu
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which statement is wrong?
- except catches errors
- else runs when no error
- finally runs only on error Correct answer
- raise throws errors
Explanation: finally always runs — error or no error.
2 Match error handling
| Term | Meaning |
|---|---|
try |
Protected code |
except |
Catches the error |
raise |
Throws an error |
finally |
Always runs |