Interview question
What is the difference between Exception and BaseException in Python? Python में Exception और BaseException में क्या अंतर है?
Answer
BaseException is the root of Python's exception hierarchy. Exception is a subclass of it that covers 'normal' errors your code should typically catch, while BaseException also includes system-exiting exceptions that usually should NOT be caught broadly.
| Direct subclasses of BaseException | Purpose |
|---|---|
| Exception | Base for all 'normal' catchable errors |
| SystemExit | Raised by sys.exit() |
| KeyboardInterrupt | Raised when user presses Ctrl+C |
| GeneratorExit | Raised when a generator is closed |
# DANGEROUS - catching BaseException swallows Ctrl+C and sys.exit() too
try:
risky_operation()
except BaseException:
pass # user can no longer Ctrl+C to stop the program!
# CORRECT - catch Exception, letting system signals propagate normally
try:
risky_operation()
except Exception as e:
print(f'Handled: {e}') # KeyboardInterrupt still works as expected
# Custom exceptions should inherit from Exception, NOT BaseException
class MyAppError(Exception): # correct
pass
# class MyAppError(BaseException): # avoid - bypasses normal 'except Exception' handlersBaseException Python की exception hierarchy की जड़ है। Exception इसका subclass है जो 'normal' errors cover करता है, जबकि BaseException system-exiting exceptions भी include करता है जिन्हें आमतौर पर broadly catch नहीं करना चाहिए।
| BaseException के direct subclasses | उद्देश्य |
|---|---|
| Exception | सभी 'normal' catchable errors का base |
| SystemExit | sys.exit() से raise होता है |
| KeyboardInterrupt | Ctrl+C दबाने पर raise होता है |
# खतरनाक - BaseException catch करना Ctrl+C भी swallow कर देता है
try:
risky_operation()
except BaseException:
pass
# सही - Exception catch करना
try:
risky_operation()
except Exception as e:
print(f'Handled: {e}')
# Custom exceptions Exception से inherit करने चाहिए, BaseException से नहीं
class MyAppError(Exception):
passWas this answer clear?