Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Question 5 of 10 · Exception Handling & Debugging
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 BaseExceptionPurpose
ExceptionBase for all 'normal' catchable errors
SystemExitRaised by sys.exit()
KeyboardInterruptRaised when user presses Ctrl+C
GeneratorExitRaised 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' handlers

BaseException Python की exception hierarchy की जड़ है। Exception इसका subclass है जो 'normal' errors cover करता है, जबकि BaseException system-exiting exceptions भी include करता है जिन्हें आमतौर पर broadly catch नहीं करना चाहिए।

BaseException के direct subclassesउद्देश्य
Exceptionसभी 'normal' catchable errors का base
SystemExitsys.exit() से raise होता है
KeyboardInterruptCtrl+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):
    pass

Was this answer clear?