CodeBlanks Logo Icon CodeBlanks

Exception hierarchy

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
└── KeyboardInterrupt

except 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

main.py
# open a try block
# catch ValueError and Exception in separate except blocks

Sample solution

main.py
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

Question
try:
    value = int("abc")
____ as e:
    print(f"hata: {e}")
Answer
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.

All lessons in Beginner