Exception hierarchy
- Python course
- Beginner
- Lesson 103/116
- 5 min
Learn ValueError, TypeError, KeyError and others.
Exception hierarchy
In Python all errors form a tree. The root is BaseException; Exception is its subclass. Common errors like ValueError, TypeError and KeyError are subclasses of Exception:
BaseException
├── Exception
│ ├── ValueError
│ ├── TypeError
│ └── KeyError
└── KeyboardInterruptexcept Exception catches all program errors but not system errors like KeyboardInterrupt. This is safer than a bare except:.
Knowing the hierarchy helps you write the right except block.
Multiple except blocks
After a single try block you can write multiple except blocks. Python reads top to bottom and runs the first match:
try:
value = int("abc")
except ValueError:
print("değer hatası")
except TypeError:
print("tür hatası")
except Exception as e:
print(f"diğer: {e}")With as e you bind the error object to a variable and access its message. Always put the most general one (Exception) last.
This lets you react differently to different error types.
Practice Catch value error with multiple except
Inside a try block write value = int("abc"). Inside an except ValueError: block write print("değer hatası"). Inside an except Exception as e: block write print(f"diğer: {e}").
Starter code
# open a try block
# catch ValueError and Exception in separate except blocksSample solution
try:
value = int("abc")
except ValueError:
print("değer hatası")
except Exception as e:
print(f"diğer: {e}")Expected output
değer hatası
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which is NOT a subclass of Exception?
- KeyboardInterrupt Correct answer
- TypeError
- KeyError
- ValueError
Explanation: KeyboardInterrupt is a direct subclass of BaseException, not Exception.
2 Match the hierarchy
| Term | Meaning |
|---|---|
BaseException |
Root class |
Exception |
Program errors |
ValueError |
Subclass |
as e |
Binds the error object |
3 Complete the except as e pattern
try:
value = int("abc")
____ as e:
print(f"hata: {e}")
try:
value = int("abc")
except Exception as e:
print(f"hata: {e}")
Explanation: except Exception as e catches all program errors and binds them to e.